Module: PollEverywhere::Serializable::InstanceMethods

Defined in:
lib/polleverywhere/serializable.rb

Instance Method Summary collapse

Instance Method Details

#from_hash(hash) ⇒ Object

Set the attributes from a hash



106
107
108
109
110
111
112
113
114
115
# File 'lib/polleverywhere/serializable.rb', line 106

def from_hash(hash)
  hash = CoreExt::HashWithIndifferentAccess.new(hash)
  # Pop off the root key if one is specified and given
  self.class.root_key and hash[self.class.root_key] and hash = hash[self.class.root_key]
  # Then set the attributes on the klass if they're present
  hash.each do |name, value|
    self.send("#{name}=", value) if self.respond_to? name
  end
  self
end

#from_json(json) ⇒ Object



121
122
123
# File 'lib/polleverywhere/serializable.rb', line 121

def from_json(json)
  from_hash JSON.parse(json)
end

#propsObject



89
90
91
92
93
94
# File 'lib/polleverywhere/serializable.rb', line 89

def props
  @props ||= self.class.props.inject CoreExt::HashWithIndifferentAccess.new do |hash, (name, property)|
    hash[property.name] = property.value
    hash
  end
end

#to_hashObject



96
97
98
99
100
101
102
103
# File 'lib/polleverywhere/serializable.rb', line 96

def to_hash
  hash = props.inject CoreExt::HashWithIndifferentAccess.new do |hash, (name, value)|
    hash[name] = self.send(name)
    hash
  end
  # Add a root key if one is specified
  self.class.root_key ? { self.class.root_key => hash } : hash
end

#to_jsonObject



117
118
119
# File 'lib/polleverywhere/serializable.rb', line 117

def to_json
  JSON.pretty_generate(to_hash)
end