Class: Module

Inherits:
Object show all
Defined in:
lib/backports/method.rb,
lib/backports/module.rb

Instance Method Summary collapse

Instance Method Details

#alias_method_chain(target, feature) {|aliased_target, punctuation| ... } ⇒ Object

Standard in rails… See official documentation

Yields:

  • (aliased_target, punctuation)


3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/backports/module.rb', line 3

def alias_method_chain(target, feature)
  # Strip out punctuation on predicates or bang methods since
  # e.g. target?_without_feature is not a valid method name.
  aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1
  yield(aliased_target, punctuation) if block_given?
  
  with_method, without_method = "#{aliased_target}_with_#{feature}#{punctuation}", "#{aliased_target}_without_#{feature}#{punctuation}"
  
  alias_method without_method, target
  alias_method target, with_method
  
  case
    when public_method_defined?(without_method)
      public target
    when protected_method_defined?(without_method)
      protected target
    when private_method_defined?(without_method)
      private target
  end
end

#instance_method_with_additional_info(name) ⇒ Object



39
40
41
42
43
44
# File 'lib/backports/method.rb', line 39

def instance_method_with_additional_info(name)
  returning instance_method_without_additional_info(name) do |unbound|
    unbound.name = name.to_sym
    unbound.owner = ancestors.find{|mod| mod.instance_methods(false).include? name.to_s}
  end
end

#make_block_optional(*methods) ⇒ Object

Metaprogramming utility to make block optional. Tests first if block is already optional when given options



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/backports/module.rb', line 29

def make_block_optional(*methods)
  options = methods.extract_options!
  methods.each do |selector|
    next unless method_defined? selector
    unless options.empty?
      test_on = options[:test_on] || self.new
      next if (test_on.send(selector, *options.fetch(:arg, [])) rescue false)
    end
    alias_method_chain(selector, :optional_block) do |aliased_target, punctuation|
      module_eval "        def \#{aliased_target}_with_optional_block\#{punctuation}(*args, &block)\n          return to_enum(:\#{aliased_target}_without_optional_block\#{punctuation}, *args) unless block_given?\n          \#{aliased_target}_without_optional_block\#{punctuation}(*args, &block)\n        end\n      end_eval\n    end\n  end\nend\n"