File: attr_optional.rb

package info (click to toggle)
ruby-attr-required 1.0.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 164 kB
  • sloc: ruby: 290; makefile: 2
file content (51 lines) | stat: -rw-r--r-- 958 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
module AttrOptional

  def self.included(klass)
    klass.send :extend, ClassMethods
  end

  module ClassMethods

    def inherited(klass)
      super
      unless optional_attributes.empty?
        klass.attr_optional *optional_attributes
      end
    end

    def attr_optional(*keys)
      if defined? undef_required_attributes
        undef_required_attributes *keys
      end
      optional_attributes.concat(keys)
      attr_accessor *keys
    end

    def attr_optional?(key)
      optional_attributes.include?(key)
    end

    def optional_attributes
      @optional_attributes ||= []
    end

    def undef_optional_attributes(*keys)
      keys.each do |key|
        if attr_optional?(key)
          undef_method key, :"#{key}="
          optional_attributes.delete key
        end
      end
    end

  end

  def optional_attributes
    self.class.optional_attributes
  end

  def attr_optional?(key)
    self.class.attr_optional? key
  end

end