Module: Blackbeard::StorableHasMany::ClassMethods

Defined in:
lib/blackbeard/storable_has_many.rb

Instance Method Summary collapse

Instance Method Details

#_has_many(plural, klass) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/blackbeard/storable_has_many.rb', line 19

def _has_many(plural, klass)
  plural = plural.to_s.downcase
  singular = klass.name.split('::').last.downcase

  methods = <<-END_OF_RUBY

      def has_#{singular}?(o)
        #{singular}_ids.include?(o.id)
      end

      def add_#{singular}(o)
        db.set_add_member(#{plural}_set_key, o.key) unless has_#{singular}?(o)
        \@#{plural} = nil
      end

      def remove_#{singular}(o)
        db.set_remove_member(#{plural}_set_key, o.key)
        \@#{plural} = nil
      end

      def #{plural}
        \@#{plural} ||= #{klass.name}.new_from_keys(#{singular}_keys)
      end

      def #{singular}_ids
        #{plural}.map{ |g| g.id }
      end

      def #{singular}_keys
        db.set_members(#{plural}_set_key)
      end

      def #{plural}_set_key
        raise StorableNotSaved if new_record?
        key+"::#{plural}"
      end
  END_OF_RUBY

  class_eval(methods)
end

#has_many(options = {}) ⇒ Object



13
14
15
16
17
# File 'lib/blackbeard/storable_has_many.rb', line 13

def has_many(options = {})
  options.each_pair do |plural, klass|
    _has_many(plural, klass)
  end
end