Module: SwingSupport::Extensions::Attributes::ClassMethods
- Defined in:
- lib/swing_support/extensions/attributes.rb
Instance Method Summary collapse
-
#attr_setter(*new_attributes) ⇒ Object
Adds settable attributes for a given class, possibly with defaults If defaults are given for attributes, they should be put at the end (as opts).
- #attributes ⇒ Object
-
#new_with_attributes(*args, &block) ⇒ Object
Sets attributes after calling original new.
Instance Method Details
#attr_setter(*new_attributes) ⇒ Object
Adds settable attributes for a given class, possibly with defaults If defaults are given for attributes, they should be put at the end (as opts)
33 34 35 36 37 38 39 40 |
# File 'lib/swing_support/extensions/attributes.rb', line 33 def attr_setter *new_attributes if new_attributes.last.is_a? Hash # Some attributes are given with defaults new_attributes_with_defaults = new_attributes.pop new_attributes_with_defaults.each { |name, default| attributes[name] = default } end new_attributes.each { |name| attributes[name] = nil } end |
#attributes ⇒ Object
27 28 29 |
# File 'lib/swing_support/extensions/attributes.rb', line 27 def attributes @attributes ||= (superclass.attributes.dup rescue {}) end |
#new_with_attributes(*args, &block) ⇒ Object
Sets attributes after calling original new
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/swing_support/extensions/attributes.rb', line 43 def new_with_attributes(*args, &block) opts = args.last.is_a?(Hash) ? args.pop.dup : {} component = self.new_without_attributes(*args, &block) # Extract known attributes given in opts, # run default actions on them, or return known defaults attributes = attributes().map do |name, default| value = opts.delete name result = if default.nil? # No default, use value directly value elsif default.respond_to? :call # Default is callable, call it with whatever value default.call *value elsif default.is_a?(Class) && value.class != default # Default class of this attribute, create new default.new *value unless value.nil? else # Return either non-nil value or default value.nil? ? default : value end [name, result] unless result.nil? end.compact attributes.each do |(name, value)| if component.respond_to? "#{name}=" component.send "#{name}=", *value elsif component.respond_to? "set_#{name}" component.send "set_#{name}", *value else raise ArgumentError.new "Setter #{name} does not work for #{component}" end end # Post-process non-setter opts (setter opts are already consumed by now) component.post_process opts # Raises exception if any of the given options left unprocessed raise "Unrecognized options: #{opts}" unless opts.empty? component end |