class Hashie::Dash
API for defining properties as well as per-property defaults.
It is preferrable to a Struct because of the in-class
resources than something like a DataMapper resource.
lightweight data object that needs even fewer options and
Dashes are useful when you need to create a very simple
optional defaults) and only those keys may be set or read.
that has a set of defined keys that are accessible (with
A Dash is a ‘defined’ or ‘discrete’ Hash, that is, a Hash
def self.inherited(klass)
def self.inherited(klass) super (@subclasses ||= Set.new) << klass klass.instance_variable_set('@properties', self.properties.dup) klass.instance_variable_set('@defaults', self.defaults.dup) end
def self.property(property_name, options = {})
Dash.
to be returned before a value is set on the property in a new
* :default - Specify a default value for this property,
as follows:
Defines a property on the Dash. Options are
def self.property(property_name, options = {}) property_name = property_name.to_sym self.properties << property_name if options[:default] or self.defaults[property_name] self.defaults[property_name] = options[:default] end unless instance_methods.map { |m| m.to_s }.include?("#{property_name}=") class_eval <<-ACCESSORS def #{property_name} _regular_reader(#{property_name.to_s.inspect}) end def #{property_name}=(value) _regular_writer(#{property_name.to_s.inspect}, value) end ACCESSORS end if defined? @subclasses @subclasses.each { |klass| klass.property(property_name, options) } end end
def self.property?(name)
Check to see if the specified property has already been
def self.property?(name) properties.include? name.to_sym end
def [](property)
Retrieve a value from the Dash (will return the
def [](property) assert_property_exists! property super(property.to_s) end
def []=(property, value)
Set a value on the Dash in a Hash-like way. Only works
def []=(property, value) assert_property_exists! property super(property.to_s, value) end
def assert_property_exists!(property)
def assert_property_exists!(property) unless self.class.property?(property) raise NoMethodError, "The property '#{property}' is not defined for this Dash." end end
def initialize(attributes = {}, &block)
You may initialize a Dash with an attributes hash
def initialize(attributes = {}, &block) super(&block) self.class.defaults.each_pair do |prop, value| self.send("#{prop}=", value) end attributes.each_pair do |att, value| self.send("#{att}=", value) end if attributes end