gouf
9/14/2014 - 7:02 AM

The magic of methodmissing on Ruby

The magic of methodmissing on Ruby

require 'active_support'
require 'active_support/core_ext'

class Test
  def method_missing(name, *args, &block)
    names = %w(node page part)
    super unless names.include?(name)
  
    name_space = args.first.gsub('/', '_')
    path = ".:site/#{name}/#{name_space}"
    opts = {
      as: "#{name_space}_page",
      path: path,
      module: "cms"
    }
    namespace(name_space, opts) { yield }
  end
end
class String
  def method_missing(name, *args, &block)
    if %w(style alt id class href).include?(name.to_s)
    # if name.to_s.eql?('style')
      str = self
      tag = str.match(/^<(.+)>.+/).captures.first
      if tag.length > 10
        end_tag = tag.match(/([^\s]+)/).captures.first
      else
        end_tag = tag
      end
      body = str.match(/^<.+>(.+)<\/.+>/).captures.first
      # p tag, body, args.join
      "<#{tag} #{name}=\"#{args.join}\">#{body}</#{end_tag}>"
    else
      super
    end
  end
end

class Tagging
  def method_missing(name, *args, &block)
    tag = name.to_s.split('=').first
    formatted_string = "<#{tag}>#{args.join}</#{tag}>"
    if tag.empty?
      p 'empty'
      super
    else
      formatted_string
    end
  end
end

tag = Tagging.new
# p tag.h1 'hogehoge'
puts tag.h1('some text').style('background: silver;')
puts tag.pre('some text').alt('background')
puts tag.a('some text').alt('background').href('http://exmpale.com')
puts tag.div('some text').style('background: orange;')

# <h1 style="background: silver;">some text</h1>
# <pre alt="background">some text</pre>
# <a alt="background" href="http://exmpale.com">some text</a>
# <div style="background: orange;">some text</div>
class Test < StandardError
  def method_missing(name, *args)
    _raise, status_code = name.to_s.split('_')
    super unless _raise.eql?('raise') && status_code.to_i > 0
    trigger = yield rescue false
    raise status_code unless trigger
  end
end

t = Test.new
t.raise_500