Module: PollEverywhere::Serializable::InstanceMethods

Defined in:
lib/polleverywhere/serializable.rb

Instance Method Summary collapse

Instance Method Details

#changed?Boolean

Figure out if the model changed.

Returns:

  • (Boolean)


180
181
182
# File 'lib/polleverywhere/serializable.rb', line 180

def changed?
  value_set.changed?
end

#from_hash(hash) ⇒ Object

Set the attributes from a hash



201
202
203
204
205
206
207
208
209
210
# File 'lib/polleverywhere/serializable.rb', line 201

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



216
217
218
# File 'lib/polleverywhere/serializable.rb', line 216

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

#prop(name) ⇒ Object

Returns a value from the value_set for a property



175
176
177
# File 'lib/polleverywhere/serializable.rb', line 175

def prop(name)
  value_set.prop(name)
end

#to_hashObject



184
185
186
187
188
189
190
191
# File 'lib/polleverywhere/serializable.rb', line 184

def to_hash
  hash = value_set.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



212
213
214
# File 'lib/polleverywhere/serializable.rb', line 212

def to_json
  JSON.pretty_generate(to_hash)
end

#to_sObject

Debug friendly way to output model state



194
195
196
197
198
# File 'lib/polleverywhere/serializable.rb', line 194

def to_s
  %(#{self.class.name}(#{value_set.props.map{|name, val|
    "#{name}:#{'`' if val.changed? }#{val.current.inspect}"
  }.join(', ')}))
end

#value_setObject

A value set instance for this class instance



170
171
172
# File 'lib/polleverywhere/serializable.rb', line 170

def value_set
  @value_set ||= self.class.prop_set.value_set
end