1 # Copyright 2008 Dag Odenhall <dag.odenhall@gmail.com>
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 require 'amazing/helpers/lazy_data'
16 require 'amazing/helpers/pango_markup'
21 # Raised by widgets, and is then rescued and logged
22 class WidgetError < Exception
25 # Parent class for widget construction, example:
27 # class Clock < Widget
28 # description "Displays date and time"
29 # dependency "some/library", "how to get the library (url, gem name...)"
30 # option :time_format, "Time format as described in DATE(1)", "%R"
31 # field :time, "Formatted time"
35 # @time = Time.now.strftime(@time_format)
36 # raise WidgetError, "An error occured!" if some_error?
40 include Helpers::LazyData
41 include Helpers::PangoMarkup
44 def initialize(opts={})
45 self.class.dependencies.each do |name, description|
49 raise WidgetError, "Missing dependency #{name.inspect}#{if description then " [#{description}]" end}"
52 self.class.options.each do |key, value|
53 instance_variable_set "@#{key}".to_sym, value[:default]
55 opts.each do |key, value|
56 instance_variable_set "@#{key}".to_sym, value
58 self.class.fields.each do |key, value|
59 instance_variable_set "@#{key}".to_sym, value[:default]
61 self.class.init.each do |block|
64 @default = case self.class.default
66 instance_eval(&self.class.default)
68 instance_eval(self.class.default)
72 def self.description(description=nil)
74 @description = description
80 def self.dependency(name, description=nil)
82 @dependencies[name] = description
89 def self.option(name, description=nil, default=nil)
91 @options[name] = {:description => description, :default => default}
98 def self.field(name, description=nil, default=nil)
100 @fields[name] = {:description => description, :default => default}
107 def self.default(format=nil, &block) # :yields:
117 def self.init(&block) # :yields:
126 def formatize(format=nil)
129 instance_eval(&format)
131 instance_eval(format)
133 case self.class.default
135 instance_eval(&self.class.default)
137 instance_eval(self.class.default)
139 end.to_s).result(binding())