A Dash is a 'defined' or 'discrete' Hash, that is, a Hash that has a set of defined keys that are accessible (with optional defaults) and only those keys may be set or read.
Dashes are useful when you need to create a very simple lightweight data object that needs even fewer options and resources than something like a DataMapper resource.
It is preferrable to a Struct because of the in-class API for defining properties as well as per-property defaults.
# File lib/hashie/dash.rb, line 69 def self.inherited(klass) super (@subclasses ||= Set.new) << klass klass.instance_variable_set('@properties', properties.dup) klass.instance_variable_set('@getters', getters.dup) klass.instance_variable_set('@defaults', defaults.dup) klass.instance_variable_set('@required_properties', required_properties.dup) end
Defines a property on the Dash. Options are as follows:
:default
- Specify a default value for this property, to be
returned before a value is set on the property in a new Dash.
:required
- Specify the value as required for this property,
to raise an error if a value is unset in a new or existing Dash. If a Proc is provided, it will be run in the
context of the Dash instance. If a Symbol is
provided, the property it represents must not be nil. The property is only
required if the value is truthy.
:message
- Specify custom error message for required property
# File lib/hashie/dash.rb, line 36 def self.property(property_name, options = {}) properties << property_name if options.key?(:default) defaults[property_name] = options[:default] elsif defaults.key?(property_name) defaults.delete property_name end define_getter_for(property_name) define_setter_for(property_name) @subclasses.each { |klass| klass.property(property_name, options) } if defined? @subclasses condition = options.delete(:required) if condition message = options.delete(:message) || "is required for #{name}." required_properties[property_name] = { condition: condition, message: message } elsif options.key?(:message) raise ArgumentError, 'The :message option should be used with :required option.' end end
Check to see if the specified property has already been defined.
# File lib/hashie/dash.rb, line 80 def self.property?(name) properties.include? name end
Check to see if the specified property is required.
# File lib/hashie/dash.rb, line 86 def self.required?(name) required_properties.key? name end