lib/chozo/varia_model.rb in chozo-0.3.0 vs lib/chozo/varia_model.rb in chozo-0.4.0
- old
+ new
@@ -1,5 +1,6 @@
+require 'multi_json'
require 'chozo/core_ext'
require 'chozo/hashie_ext'
module Chozo
# @author Jamie Winsor <jamie@vialstudios.com>
@@ -168,21 +169,63 @@
# @return [HashWithIndifferentAccess]
def errors
@errors ||= HashWithIndifferentAccess.new
end
+ def mass_assign(new_attrs = {})
+ attributes.dotted_paths.each do |dotted_path|
+ value = new_attrs.dig(dotted_path)
+ next if value.nil?
+
+ set_attribute(dotted_path, value)
+ end
+ end
+ alias_method :attributes=, :mass_assign
+
# @param [#to_s] key
#
# @return [Object]
def get_attribute(key)
self.attributes.dig(key.to_s)
end
+ alias_method :[], :get_attribute
# @param [#to_s] key
# @param [Object] value
def set_attribute(key, value)
self.attributes.deep_merge!(attributes.class.from_dotted_path(key.to_s, value))
end
+ alias_method :[]=, :set_attribute
+
+ # @param [#to_hash] hash
+ #
+ # @return [self]
+ def from_hash(hash)
+ mass_assign(hash.to_hash)
+ self
+ end
+
+ # @param [String] data
+ #
+ # @return [self]
+ def from_json(data)
+ mass_assign(MultiJson.decode(data))
+ self
+ end
+
+ # @return [Hash]
+ def to_hash
+ self.attributes
+ end
+
+ # @option options [Boolean] :symbolize_keys
+ # @option options [Class, Symbol, String] :adapter
+ #
+ # @return [String]
+ def to_json(options = {})
+ MultiJson.encode(self.attributes, options)
+ end
+ alias_method :as_json, :to_json
protected
# @param [String] attribute
# @param [String] message