Class: YamlRecord::Base

Inherits:
Object
  • Object
show all
Includes:
ActiveSupport::Callbacks
Defined in:
lib/ruby_home/yaml_record.rb

Direct Known Subclasses

RubyHome::AccessoryInfo

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attr_hash = {}) ⇒ Base

Constructs a new YamlRecord instance based on specified attribute hash

Example:

class Post < YamlRecord::Base; properties :foo; end

Post.new(:foo  => "bar")


53
54
55
56
57
58
59
60
61
62
# File 'lib/ruby_home/yaml_record.rb', line 53

def initialize(attr_hash={})
  attr_hash.symbolize_keys!
  attr_hash.reverse_merge!(self.class.properties.inject({}) { |result, key| result[key] = nil; result })

  self.attributes ||= {}
  self.is_created = attr_hash.delete(:persisted) || false
  attr_hash.each do |k,v|
    self.send("#{k}=", v) # self.attributes[:media] = "foo"
  end
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



38
39
40
# File 'lib/ruby_home/yaml_record.rb', line 38

def attributes
  @attributes
end

#is_createdObject

Returns the value of attribute is_created.



38
39
40
# File 'lib/ruby_home/yaml_record.rb', line 38

def is_created
  @is_created
end

#is_destroyedObject

Returns the value of attribute is_destroyed.



38
39
40
# File 'lib/ruby_home/yaml_record.rb', line 38

def is_destroyed
  @is_destroyed
end

Class Method Details

.adapter(kind = nil, *options) ⇒ Object

Declares or retrieves adapter for Yaml storage Returns an instance of an adapter

Example:

class Post < YamlRecord::Base
  adapter :redis, @redis #  => YamlRecord::Adapters::RedisAdapter
end


372
373
374
375
# File 'lib/ruby_home/yaml_record.rb', line 372

def self.adapter(kind=nil, *options)
  kind.nil? ? @_adapter_kind ||= :local : @_adapter_kind = kind
  @_adapter ||= eval("YamlRecord::Adapters::#{@_adapter_kind.to_s.capitalize}Store").new(*options)
end

.allObject

Returns collection of all YamlRecord instances Caches results during request

Example:

Post.all  => [@post1, @post2, ...]
Post.all(true) => (...force reload...)


299
300
301
302
# File 'lib/ruby_home/yaml_record.rb', line 299

def self.all
  raw_items = self.adapter.read(self.source) || []
  raw_items.map { |item| self.new(item.merge(:persisted => true)) }
end

.create(attributes = {}) ⇒ Object

Initializes YamlRecord instance given an attribute hash and saves afterwards Returns instance if successfully saved; false otherwise

Example:

Post.create(:foo => "bar", :miso => "great")  => @post


335
336
337
338
339
340
341
342
343
# File 'lib/ruby_home/yaml_record.rb', line 335

def self.create(attributes={})
  @fs = self.new(attributes)
  if @fs.save == true
    @fs.is_created = true
    @fs
  else
    false
  end
end

.find_by_attribute(attribute, expected_value) ⇒ Object

Find YamlRecord instance given attribute name and expected value Supports checking inclusion for array based values Returns instance if found; false otherwise

Example:

Post.find_by_attribute(:foo, "bar")         => @post
Post.find_by_attribute(:some_list, "item")  => @post


267
268
269
270
271
272
273
274
# File 'lib/ruby_home/yaml_record.rb', line 267

def self.find_by_attribute(attribute, expected_value)
  self.all.find do |record|
    value = record.send(attribute) if record.respond_to?(attribute)
    value.is_a?(Array) ?
      value.include?(expected_value) :
      value == expected_value
  end
end

.find_by_id(value) ⇒ Object Also known as: find

Find YamlRecord instance given id Returns instance if found; false otherwise

Example:

Post.find_by_id("a1b2c3")  => @post


285
286
287
# File 'lib/ruby_home/yaml_record.rb', line 285

def find_by_id(value)
  self.find_by_attribute(:id, value)
end

.first(limit = 1) ⇒ Object

Find first YamlRecord instance given a limit Returns an array of instances if found; empty otherwise

Example:

Post.first  => @post
Post.first(3) => [@p1, @p2, @p3]


324
325
326
# File 'lib/ruby_home/yaml_record.rb', line 324

def self.first(limit=1)
  limit == 1 ? self.all.first : self.all.first(limit)
end

.last(limit = 1) ⇒ Object

Find last YamlRecord instance given a limit Returns an array of instances if found; empty otherwise

Example:

Post.last  => @post6
Post.last(3) => [@p4, @p5, @p6]


312
313
314
# File 'lib/ruby_home/yaml_record.rb', line 312

def self.last(limit=1)
  limit == 1 ? self.all.last : self.all.last(limit)
end

.properties(*names) ⇒ Object

Declares persisted attributes for YamlRecord class

Example:

class Post < YamlRecord::Base; properties :foo, :miso; end
Post.create(:foo => "bar", :miso => "great")  => @post


352
353
354
355
356
357
358
359
360
361
# File 'lib/ruby_home/yaml_record.rb', line 352

def self.properties(*names)
  @_properties ||= []
  if names.size == 0 # getter
    @_properties
  elsif names.size > 0 # setter
    names = names | [:id]
    setup_properties!(*names)
    @_properties += names
  end
end

.setup_properties!(*names) ⇒ Object

Creates reader and writer methods for each persisted attribute Protected method, not called during usage

Example:

Post.setup_properties!(:foo)
@post.foo = "baz"
@post.foo => "baz"


425
426
427
428
429
430
# File 'lib/ruby_home/yaml_record.rb', line 425

def self.setup_properties!(*names)
  names.each do |name|
    define_method(name) { self[name.to_sym] }
    define_method("#{name}=") { |val| self[name.to_sym] = val  }
  end
end

.source(file = nil) ⇒ Object

Declares source file for YamlRecord class

Example:

class Post < YamlRecord::Base
  source "path/to/yaml/file"
end


385
386
387
# File 'lib/ruby_home/yaml_record.rb', line 385

def self.source(file=nil)
  file ? @file = (file.to_s) : @file
end

.validates_each(*args, &block) ⇒ Object

Validates each persisted attributes TODO Implement validation



400
401
402
# File 'lib/ruby_home/yaml_record.rb', line 400

def self.validates_each(*args, &block)
  true
end

.write_contents(raw_data) ⇒ Object

Write raw yaml data to file Protected method, not called during usage

Example:

Post.write_content([{ :foo => "bar"}, { :foo => "baz"}, ...]) # writes to source file


411
412
413
414
# File 'lib/ruby_home/yaml_record.rb', line 411

def self.write_contents(raw_data)
  self.adapter.write(self.source, raw_data)
  @records = nil
end

Instance Method Details

#==(comparison_record) ⇒ Object

Overrides equality to match if matching ids



391
392
393
# File 'lib/ruby_home/yaml_record.rb', line 391

def ==(comparison_record)
  self.id == comparison_record.id
end

#[](attribute) ⇒ Object

Accesses given attribute from YamlRecord instance

Example:

@post[:foo] => "bar"


70
71
72
# File 'lib/ruby_home/yaml_record.rb', line 70

def [](attribute)
  self.attributes[attribute]
end

#[]=(attribute, value) ⇒ Object

Assign given attribute from YamlRecord instance with specified value

Example:

@post[:foo] = "baz"


80
81
82
# File 'lib/ruby_home/yaml_record.rb', line 80

def []=(attribute, value)
  self.attributes[attribute] = value
end

#column_namesObject

Returns array of instance attributes names; An attribute is a value stored for this record (persisted or not)

Example:

@post.column_names => ["foo", "miso"]


133
134
135
# File 'lib/ruby_home/yaml_record.rb', line 133

def column_names
  self.attributes.keys.map(&:to_s)
end

#destroyObject

Remove a persisted YamlRecord object Returns true if destroyed; false otherwise

Example:

@post = Post.create(:foo => "bar", :miso => "great")
Post.all.size => 1
@post.destroy  => true
Post.all.size => 0


187
188
189
190
191
192
193
194
195
196
# File 'lib/ruby_home/yaml_record.rb', line 187

def destroy
  run_callbacks(:before_destroy)
  new_data = self.class.all.reject { |item| item.persisted_attributes == self.persisted_attributes }.map { |item| item.persisted_attributes }
  self.class.write_contents(new_data)
  self.is_destroyed = true
  run_callbacks(:after_destroy)
  true
rescue IOError
  false
end

#destroyed?Boolean

Returns true if YamlRecord instance has been destroyed; false otherwise

Example:

@post = Post.new(:foo => "bar", :miso => "great")
@post.destroyed?  =>  false
@post.save
@post.destroy  => true
@post.destroyed?  =>  true

Returns:

  • (Boolean)


173
174
175
# File 'lib/ruby_home/yaml_record.rb', line 173

def destroyed?
  self.is_destroyed
end

#errorsObject

Returns errors messages if record isn’t valid; empty array otherwise TODO Implement validation

Example:

@post.errors => ["Foo can't be blank"]


217
218
219
# File 'lib/ruby_home/yaml_record.rb', line 217

def errors
  []
end

#new_record?Boolean

Returns true if YamlRecord instance hasn’t persisted; false otherwise

Example:

@post = Post.new(:foo => "bar", :miso => "great")
@post.new_record?  =>  true
@post.save  => true
@post.new_record?  =>  false

Returns:

  • (Boolean)


159
160
161
# File 'lib/ruby_home/yaml_record.rb', line 159

def new_record?
  !self.is_created
end

#persisted_attributesObject

Returns hash of attributes to be persisted to file. A persisted attribute is a value stored in the file (specified with the properties declaration)

Example:

class Post < YamlRecord::Base; properties :foo, :miso; end
@post = Post.create(:foo => "bar", :miso => "great")
@post.persisted_attributes => { :id => "a1b2c3", :foo => "bar", :miso => "great" }


146
147
148
# File 'lib/ruby_home/yaml_record.rb', line 146

def persisted_attributes
  self.attributes.slice(*self.class.properties).reject { |k, v| v.nil? }
end

#reloadObject

Reload YamlRecord instance attributes from file

Example:

@post = Post.create(:foo => "bar", :miso => "great")
@post.foo = "bazz"
@post.reload
@post.foo => "bar"


252
253
254
255
256
# File 'lib/ruby_home/yaml_record.rb', line 252

def reload
  record = self.class.find(self.id)
  self.attributes = record.attributes
  record
end

#saveObject

Saved YamlRecord instance to file Executes save and create callbacks Returns true if record saved; false otherwise

Example:

@post.save => true


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/ruby_home/yaml_record.rb', line 92

def save
  run_callbacks(:before_save)
  run_callbacks(:before_create) unless self.is_created

  existing_items = self.class.all
  if self.new_record?
    existing_items << self
  else # update existing record
    updated_item = existing_items.find { |item| item.id == self.id }
    return false unless updated_item
    updated_item.attributes = self.attributes
  end

  raw_data = existing_items ? existing_items.map { |item| item.persisted_attributes } : []
  self.class.write_contents(raw_data) if self.valid?

  run_callbacks(:after_create) unless self.is_created
  run_callbacks(:after_save)
  true
rescue IOError
  false
end

#to_modelObject

Returns YamlRecord Instance Complies with ActiveModel api

Example:

@post.to_model => @post


228
229
230
# File 'lib/ruby_home/yaml_record.rb', line 228

def to_model
  self
end

#to_paramObject

Returns the instance of a record as a parameter By default return an id

Example:

@post.to_param => <id>


239
240
241
# File 'lib/ruby_home/yaml_record.rb', line 239

def to_param
  self.id
end

#update_attributes(updated_attrs = {}) ⇒ Object

Update YamlRecord instance with specified attributes Returns true if record updated; false otherwise

Example:

@post.update_attributes(:foo  => "baz", :miso => "awesome") => true


122
123
124
125
# File 'lib/ruby_home/yaml_record.rb', line 122

def update_attributes(updated_attrs={})
  updated_attrs.each { |k,v| self.send("#{k}=", v) }
  self.save
end

#valid?Boolean

Execute validations for instance Returns true if record is valid; false otherwise TODO Implement validation

Example:

@post.valid? => true

Returns:

  • (Boolean)


206
207
208
# File 'lib/ruby_home/yaml_record.rb', line 206

def valid?
  true
end