Module: JavaGettersAndSetters

Defined in:
lib/rpv/java/java_getters_and_setters.rb

Overview

Adds Java style getters and setters to your class. Maps (getFooBar, setFooBar, isFooBar) to (foo_bar, foo_bar=, foo_bar?). If a class implements method_missing, it should be included afterwards in order to preserve it by chaining the methods.

Constant Summary collapse

GetterRegex =
/get([A-Z]+.*)/
SetterRegex =
/set([A-Z]+.*)/
PredicateRegex =
/is([A-Z]+.*)/

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



31
32
33
34
35
36
# File 'lib/rpv/java/java_getters_and_setters.rb', line 31

def self.included(base)
  base.class_eval do
    alias_method :method_missing_without_java_getters_and_setters, :method_missing if self.instance_methods.include?("method_missing")
    alias_method :method_missing, :method_missing_with_java_getters_and_setters
  end
end

Instance Method Details

#method_missing_with_java_getters_and_setters(method, *args) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/rpv/java/java_getters_and_setters.rb', line 12

def method_missing_with_java_getters_and_setters(method, *args)
  if method.to_s =~ GetterRegex
    property = method.to_s.match(GetterRegex)[1].underscore
    self.send(property, *args)
  elsif method.to_s =~ SetterRegex
    property = method.to_s.match(SetterRegex)[1].underscore
    self.send("#{property}=", *args)
  elsif method.to_s =~ PredicateRegex
    property = method.to_s.match(PredicateRegex)[1].underscore
    self.send("#{property}?", *args)
  else
    if self.respond_to?(:method_missing_without_java_getters_and_setters)
      method_missing_without_java_getters_and_setters(method, *args)
    else
      raise NoMethodError.new("undefined method `#{method.to_s}' for #{self.to_s}", method, *args)
    end
  end
end