module NForm::Attributes::InstanceMethods
Public Class Methods
new(input=nil)
click to toggle source
# File lib/nform/attributes.rb, line 75 def initialize(input=nil) input ||= {} @__touched_keys = Set.new i = input.symbolize_keys require_attributes!(i) self.class.define_attributes set_attributes!(i) end
Public Instance Methods
to_hash()
click to toggle source
# File lib/nform/attributes.rb, line 84 def to_hash if self.class.__hash_rep == :partial @__touched_keys else self.class.attribute_set.keys end.each.with_object({}) do |k,memo| memo[k] = send(k) end end
Private Instance Methods
require_attributes!(input_hash)
click to toggle source
# File lib/nform/attributes.rb, line 95 def require_attributes!(input_hash) # Check for missing required attributes required = self.class.attribute_set.map{|name,options| name if options[:required]}.compact missing = (required - input_hash.keys) if missing.any? raise ArgumentError, "Missing required attributes: #{missing.inspect}" end # Check for unallowed extra attributes if self.class.__undef_attr == :raise extra = (input_hash.keys - self.class.attribute_set.keys) raise ArgumentError, "Undefined attribute(s): #{extra.join(',')}" if extra.any? end end
set_attributes!(input_hash)
click to toggle source
# File lib/nform/attributes.rb, line 110 def set_attributes!(input_hash) self.class.attribute_set.each do |a, opts| val = input_hash.fetch(a, opts[:default]) send "#{a}=", val if input_hash.has_key?(a) || !opts[:default].nil? end end