Class: StaticRecord::Base

Inherits:
Object
  • Object
show all
Extended by:
GatewayModel, LoaderFile
Includes:
ActiveRecord
Defined in:
lib/static_record/base.rb

Overview

This is the base class of StaticRecord.

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from GatewayModel

all, find, find_by, find_by!

Methods included from LoaderFile

database, init, load, loaded?, reload!

Methods included from ActiveRecord

#destroyed?, #new_record?

Constructor Details

#initialize(hash = {}, load = true) ⇒ Base

Returns a new instance of Base.



26
27
28
29
30
31
32
33
34
# File 'lib/static_record/base.rb', line 26

def initialize(hash = {}, load = true)
  self.class.init if load

  raise StaticRecord::StaticRecordModelInitializeError,
        "Unpermited attributes #{hash.inspect},
        it should be a hash" unless hash.is_a?(Hash)

  self.attributes = hash
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *params, &block) ⇒ Object (private)

Metaprogramming for read and set attributes through dynamic methods.



68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/static_record/base.rb', line 68

def method_missing(meth, *params, &block)
  attribute = meth.to_s.gsub(/=$/, '')

  if attribute? attribute.to_sym
    # The method missing is a setter method.
    return set_attribute attribute, params.first if meth.to_s =~ /=$/

    # The method missing is a getter method.
    return get_attribute attribute
  end

  super
end

Class Attribute Details

.file_pathObject

Returns the value of attribute file_path.



10
11
12
# File 'lib/static_record/base.rb', line 10

def file_path
  @file_path
end

Class Method Details

.file(path) ⇒ Object



16
17
18
19
20
21
22
23
# File 'lib/static_record/base.rb', line 16

def file(path)
  raise StaticRecord::FileNotFound,
        "Could not find data file #{path}" unless File.readable?(path)

  @file_path = path
  @records = nil
  @loaded = false
end

Instance Method Details

#attribute?(attribute) ⇒ Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/static_record/base.rb', line 48

def attribute?(attribute)
  attributes_keys.include?(attribute)
end

#attributesObject



40
41
42
# File 'lib/static_record/base.rb', line 40

def attributes
  @attributes ||= {}
end

#attributes=(hash) ⇒ Object



36
37
38
# File 'lib/static_record/base.rb', line 36

def attributes=(hash)
  hash.each { |k, v| set_attribute(k, v) }
end

#attributes_keysObject



44
45
46
# File 'lib/static_record/base.rb', line 44

def attributes_keys
  attributes.keys.collect(&:to_sym)
end

#to_sObject



52
53
54
# File 'lib/static_record/base.rb', line 52

def to_s
  "<#{self.class} 0x#{object_id.to_s 16}> #{@attributes.inspect}"
end