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|
53 raise WidgetError, "Missing dependency #{name.inspect}#{if description then " [#{description}]" end}"
57 self.class.options.each do |key, value|
58 instance_variable_set "@#{key}".to_sym, value[:default]
60 opts.each do |key, value|
61 instance_variable_set "@#{key}".to_sym, value
63 self.class.fields.each do |key, value|
64 instance_variable_set "@#{key}".to_sym, value[:default]
66 self.class.init.each do |block|
69 @default = case self.class.default
71 instance_eval(&self.class.default)
73 instance_eval(self.class.default)
77 def self.description(description=nil)
79 @description = description
85 def self.dependency(name, description=nil)
87 @dependencies[name] = description
94 def self.option(name, description=nil, default=nil)
96 @options[name] = {:description => description, :default => default}
103 def self.field(name, description=nil, default=nil)
105 @fields[name] = {:description => description, :default => default}
112 def self.default(format=nil, &block) # :yields:
122 def self.init(&block) # :yields:
131 def formatize(format=nil)
134 instance_eval(&format)
136 instance_eval(format)
138 case self.class.default
140 instance_eval(&self.class.default)
142 instance_eval(self.class.default)
144 end.to_s).result(binding())