Module: Ymodel::Loadable

Included in:
Base
Defined in:
lib/ymodel/loadable.rb

Overview

Module resposible for loading the schema and data from the yaml files.

Instance Method Summary collapse

Instance Method Details

#default_attribute(attr_name, with: nil) ⇒ Object

With is used as the default value of the attribute



29
30
31
32
# File 'lib/ymodel/loadable.rb', line 29

def default_attribute(attr_name, with: nil)
  @schema << attr_name
  define_reader attr_name, default: with
end

#define_reader(attribute, default: nil) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/ymodel/loadable.rb', line 77

def define_reader(attribute, default: nil)
  define_method(attribute.to_sym) do
    value = instance_variable_get("@#{attribute}")
    if value.nil? && !default.nil?
      value = instance_variable_set(
        "@#{attribute}",
        default.respond_to?(:call) ? default.call : default
      )
    end

    value
  end
end

#indexObject



65
66
67
# File 'lib/ymodel/loadable.rb', line 65

def index
  @index || :id
end

#index_on(key) ⇒ Object



60
61
62
63
# File 'lib/ymodel/loadable.rb', line 60

def index_on(key)
  @manual_index = true
  @index = key
end

#load_records!Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/ymodel/loadable.rb', line 45

def load_records!
  if load_indices?
    all = records.each_with_index
        .map { |record, i| new(record.merge({id: i})) }
  else
    all = records.map { |record| new(record) }
  end
  unless all.map(&:index) == all.map(&:index).uniq
    raise DuplicateIndexError,
          "#{name}: Some records share the same index"
  end

  all
end

#pears_subject(subject) ⇒ Object



17
18
19
20
21
22
23
24
25
26
# File 'lib/ymodel/loadable.rb', line 17

def pears_subject(subject)
  @pears = true
  if block_given?
    @source = Pears.subject(subject) { |provider| yield(provider) }
  else
    @source = subject
  end
  # Similar to Trigger#inherited. A hook for loading the schema.
  define_readers self
end

#schemaObject



34
35
36
37
38
39
40
41
42
43
# File 'lib/ymodel/loadable.rb', line 34

def schema
  @schema = Schema.new(records, index)
  if @manual_index
    @schema ||= Schema.new(records)
  else
    @schema ||= Schema.new(records, :id)
  end
rescue Errno::ENOENT => e
  Schema.new({})
end

#source_file(filename) ⇒ Object

This method can be called from within a concrete implementation to overwrite the default ymodel filename associated with that model.



10
11
12
13
14
15
# File 'lib/ymodel/loadable.rb', line 10

def source_file(filename)
  @source = filename

  # Similar to Trigger#inherited. A hook for loading the schema.
  define_readers self
end

#source_filesObject



69
70
71
72
73
74
75
# File 'lib/ymodel/loadable.rb', line 69

def source_files
  if compiled?
    Dir.glob(File.join(source, '*.yml'))
  else
    [@source]
  end
end