Class: HashieModel::Base

Inherits:
Hashie2::Dash
  • Object
show all
Extended by:
ActiveModel::Naming
Includes:
ActiveModel::AttributeMethods, ActiveModel::Conversion, ActiveModel::Validations, Hashie2::Extensions::Coercion
Defined in:
lib/hashie_model/base.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_json(json) ⇒ Object



38
39
40
# File 'lib/hashie_model/base.rb', line 38

def from_json(json)
  new(ActiveSupport::JSON.decode(json))
end

.prop(name, type = nil, options = {}) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/hashie_model/base.rb', line 14

def prop(name, type = nil, options = {})
  if type.is_a?(Hash)
    options = type
    type    = nil
  end
  
  property(name, options)

  self.superclass.key_coercions.each_pair { |key, into| coerce_key(key, into) }

  if type
    coerce_key(name.to_sym, type)
    coerce_key(name.to_s, type)
  end
  
  define_attribute_methods [name]
  alias_method :"#{name}_without_type_cast=", :"#{name}="
  
  define_method(:"#{name}=") do |value|
    attributes_before_type_cast[name.to_s] = value
    send(:"#{name}_without_type_cast=", value)
  end
end

.validates_associated(*attr_names) ⇒ Object



42
43
44
# File 'lib/hashie_model/base.rb', line 42

def validates_associated(*attr_names)
  validates_with HashieModel::AssociatedValidator, _merge_attributes(attr_names)
end

Instance Method Details

#attributesObject



61
62
63
64
65
66
67
# File 'lib/hashie_model/base.rb', line 61

def attributes
  {}.tap do |attrs|
    self.class.properties.each do |key|
      attrs[key] = self[key]
    end
  end
end

#attributes_before_type_castObject



57
58
59
# File 'lib/hashie_model/base.rb', line 57

def attributes_before_type_cast
  @attributes_before_type_cast ||= {}
end

#dupObject



69
70
71
# File 'lib/hashie_model/base.rb', line 69

def dup
  self.class.new(to_hash)
end

#encode_with(coder) ⇒ Object



53
54
55
# File 'lib/hashie_model/base.rb', line 53

def encode_with(coder)
  coder.represent_map(coder.tag, self)
end

#init_with(coder) ⇒ Object



47
48
49
50
51
# File 'lib/hashie_model/base.rb', line 47

def init_with(coder)
  coder.map.each do |k, v|
    self.send(:"#{k}=", v)
  end
end

#merge(options) ⇒ Object



73
74
75
76
77
# File 'lib/hashie_model/base.rb', line 73

def merge(options)
  h = to_hash
  h.merge!(options.stringify_keys)
  return h
end

#persisted?Boolean

Returns:

  • (Boolean)


79
80
81
# File 'lib/hashie_model/base.rb', line 79

def persisted?
  false
end