File: attr.rb

package info (click to toggle)
ruby-facets 2.9.2-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 9,824 kB
  • sloc: ruby: 25,483; xml: 90; makefile: 20
file content (82 lines) | stat: -rw-r--r-- 1,491 bytes parent folder | download
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
class Module

  # Create a toggle attribute. This creates two methods for
  # each given name. One is a form of tester and the other
  # is used to toggle the value.
  #
  #   attr_accessor! :a
  #
  # is equivalent to
  #
  #   def a?
  #     @a
  #   end
  #
  #   def a!(value=true)
  #     @a = value
  #     self
  #   end
  #
  # CREDIT: Trans

  def attr_accessor!(*args)
    attr_reader!(*args) + attr_writer!(*args)
  end

  alias_method :attr_toggler,  :attr_accessor!
  alias_method :alias_switcher, :alias_accessor!

  # Create aliases for flag accessors.
  #
  # CREDIT: Trans

  def alias_accessor!(*args)
    orig = args.last
    args = args - [orig]
    args.each do |name|
      alias_method("#{name}?", "#{orig}?")
      alias_method("#{name}!", "#{orig}!")
    end
  end

  # Create a flaggable attribute. This creates a single methods
  # used to set an attribute to "true".
  #
  #   attr_writer! :a
  #
  # is equivalent to
  #
  #   def a!(value=true)
  #     @a = value
  #     self
  #   end
  #
  def attr_writer!(*args)
    code, made = '', []
    args.each do |a|
      code << %{
        def #{a}!(value=true)
          @#{a} = value
          self
        end
      }
      made << "#{a}!".to_sym
    end
    module_eval code
    made
  end

  # Create aliases for flag writer.
  #
  # CREDIT: Trans

  def alias_writer!(*args)
    orig = args.last
    args = args - [orig]
    args.each do |name|
      alias_method("#{name}!", "#{orig}!")
    end
  end

end