lib/varia_model.rb in varia_model-0.1.1 vs lib/varia_model.rb in varia_model-0.2.0

- old
+ new

@@ -212,11 +212,11 @@ # @param [#to_s] key # # @return [Object] def get_attribute(key) - _attributes_.dig(key.to_s) + eval_as_proc(_attributes_.dig(key.to_s)) end alias_method :[], :get_attribute # @param [#to_s] key # @param [Object] value @@ -252,23 +252,36 @@ # @option options [Boolean] :symbolize_keys # @option options [Class, Symbol, String] :adapter # # @return [String] def to_json(options = {}) - JSON.generate(_attributes_, options) + JSON.generate(to_hash, options) end alias_method :as_json, :to_json + # Convert the object to a hash. + def to_hash + _attributes_.inject({}) { |h, (k,v)| h[k] = eval_as_proc(v); h } + end + protected # @param [String] attribute # @param [String] message def add_error(attribute, message) self.errors[attribute] ||= Array.new self.errors[attribute] << message end private + + # Send #call to the given object if it responds to it. If it doesn't, just return the + # object. + # + # @param [#call] + def eval_as_proc(obj) + obj.respond_to?(:call) ? obj.call : obj + end def carefree_assign(new_attrs = {}) _attributes_.deep_merge!(new_attrs) end