Class: YamlRecord::Base

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Callbacks, ActiveModel::Conversion, ActiveModel::Validations, ActiveModel::Validations::Callbacks
Defined in:
lib/yaml_record/base.rb

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")


24
25
26
27
28
29
30
31
32
33
# File 'lib/yaml_record/base.rb', line 24

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.



5
6
7
# File 'lib/yaml_record/base.rb', line 5

def attributes
  @attributes
end

#is_createdObject

Returns the value of attribute is_created.



5
6
7
# File 'lib/yaml_record/base.rb', line 5

def is_created
  @is_created
end

#is_destroyedObject

Returns the value of attribute is_destroyed.



5
6
7
# File 'lib/yaml_record/base.rb', line 5

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


345
346
347
348
# File 'lib/yaml_record/base.rb', line 345

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

.all(dynamic_source = 'default') ⇒ Object

Returns collection of all YamlRecord instances Caches results during request

Example:

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


272
273
274
275
# File 'lib/yaml_record/base.rb', line 272

def self.all(dynamic_source='default')
  raw_items = self.adapter.read(self.source, dynamic_source, self.source_file_name) || []
  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


308
309
310
311
312
313
314
315
316
# File 'lib/yaml_record/base.rb', line 308

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

.find_by_attribute(dynamic_source = 'default', 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


240
241
242
243
244
245
246
247
# File 'lib/yaml_record/base.rb', line 240

def self.find_by_attribute(dynamic_source='default', attribute, expected_value)
  self.all(dynamic_source).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(dynamic_source = 'default', value) ⇒ Object Also known as: find

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

Example:

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


258
259
260
# File 'lib/yaml_record/base.rb', line 258

def find_by_id(dynamic_source='default', value)
  self.find_by_attribute(dynamic_source, :id, value)
end

.first(dynamic_source = 'default', 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]


297
298
299
# File 'lib/yaml_record/base.rb', line 297

def self.first(dynamic_source='default', limit=1)
  limit == 1 ? self.all(dynamic_source).first : self.all(dynamic_source).first(limit)
end

.last(dynamic_source = 'default', 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]


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

def self.last(dynamic_source='default', limit=1)
  limit == 1 ? self.all(dynamic_source).last : self.all(dynamic_source).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


325
326
327
328
329
330
331
332
333
334
# File 'lib/yaml_record/base.rb', line 325

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

.source(file = nil) ⇒ Object

Declares source file for YamlRecord class

Example:

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


358
359
360
# File 'lib/yaml_record/base.rb', line 358

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

.source_file_name(source_file_name = nil) ⇒ Object

Declares source_file_name for YamlRecord class

Example:

class Post < YamlRecord::Base
  source_file_name "file_name"
end


370
371
372
# File 'lib/yaml_record/base.rb', line 370

def self.source_file_name(source_file_name=nil)
  source_file_name ? @source_file_name = (source_file_name.to_s + ".yml") : @source_file_name
end

Instance Method Details

#==(comparison_record) ⇒ Object

Overrides equality to match if matching ids



376
377
378
# File 'lib/yaml_record/base.rb', line 376

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

#[](attribute) ⇒ Object

Accesses given attribute from YamlRecord instance

Example:

@post[:foo] => "bar"


41
42
43
# File 'lib/yaml_record/base.rb', line 41

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

#[]=(attribute, value) ⇒ Object

Assign given attribute from YamlRecord instance with specified value

Example:

@post[:foo] = "baz"


51
52
53
# File 'lib/yaml_record/base.rb', line 51

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"]


104
105
106
107
108
# File 'lib/yaml_record/base.rb', line 104

def column_names
  array = []
  self.attributes.each_key { |k| array << k.to_s }
  array
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


160
161
162
163
164
165
166
167
168
169
# File 'lib/yaml_record/base.rb', line 160

def destroy
  run_callbacks(:destroy) { false }
  new_data = self.class.all.reject { |item| item.persisted_attributes == self.persisted_attributes }.map { |item| item.persisted_attributes }
  self.class.write_contents(dynamic_source, new_data)
  self.is_destroyed = true
  run_callbacks(:destroy) { true }
  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)


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

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"]


190
191
192
# File 'lib/yaml_record/base.rb', line 190

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)


132
133
134
# File 'lib/yaml_record/base.rb', line 132

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" }


119
120
121
# File 'lib/yaml_record/base.rb', line 119

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"


225
226
227
228
229
# File 'lib/yaml_record/base.rb', line 225

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


63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/yaml_record/base.rb', line 63

def save
  run_callbacks(:save) { false }
  run_callbacks(:create) { false } unless self.is_created

  existing_items = self.class.all(dynamic_source)
  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(dynamic_source, raw_data) if self.valid?

  run_callbacks(:create) { true } unless self.is_created
  run_callbacks(:save) { true }
  true
rescue IOError
  false
end

#to_modelObject

Returns YamlRecord Instance Complies with ActiveModel api

Example:

@post.to_model => @post


201
202
203
# File 'lib/yaml_record/base.rb', line 201

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>


212
213
214
# File 'lib/yaml_record/base.rb', line 212

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


93
94
95
96
# File 'lib/yaml_record/base.rb', line 93

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)


179
180
181
# File 'lib/yaml_record/base.rb', line 179

def valid?
  true
end