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/pango_markup'
20 # Raised by widgets, and is then rescued and logged
21 class WidgetError < Exception
24 # Parent class for widget construction, example:
26 # class Clock < Widget
27 # description "Displays date and time"
28 # dependency "some/library", "how to get the library (url, gem name...)"
29 # option :time_format, "Time format as described in DATE(1)", "%R"
30 # field :time, "Formatted time"
34 # @time = Time.now.strftime(@time_format)
35 # raise WidgetError, "An error occured!" if some_error?
39 include Helpers::PangoMarkup
42 def initialize(opts={})
43 self.class.dependencies.each do |name, description|
47 raise WidgetError, "Missing dependency #{name.inspect}#{if description then " [#{description}]" end}"
50 self.class.options.each do |key, value|
51 instance_variable_set "@#{key}".to_sym, value[:default]
53 opts.each do |key, value|
54 instance_variable_set "@#{key}".to_sym, value
56 self.class.fields.each do |key, value|
57 instance_variable_set "@#{key}".to_sym, value[:default]
59 self.class.init.each do |block|
62 @default = case self.class.default
64 instance_eval(&self.class.default)
66 instance_eval(self.class.default)
70 def self.description(description=nil)
72 @description = description
78 def self.dependency(name, description=nil)
80 @dependencies[name] = description
87 def self.option(name, description=nil, default=nil)
89 @options[name] = {:description => description, :default => default}
96 def self.field(name, description=nil, default=nil)
98 @fields[name] = {:description => description, :default => default}
105 def self.default(format=nil, &block) # :yields:
115 def self.init(&block) # :yields:
124 def formatize(format=nil)
127 instance_eval(&format)
129 instance_eval(format)
131 case self.class.default
133 instance_eval(&self.class.default)
135 instance_eval(self.class.default)
137 end.to_s).result(binding())