Skip to content

Instantly share code, notes, and snippets.

@rafaelss
Created July 19, 2012 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafaelss/3144043 to your computer and use it in GitHub Desktop.
Save rafaelss/3144043 to your computer and use it in GitHub Desktop.
class Code
def initialize(code)
@code = code
end
def process
parse(transform(@code))
end
def transform(code)
parts = code.split("|")
chain = [parts.first]
parts[1..-1].each_with_index do |m, i|
_, meth, *args = m.strip.split(/^([^:]+):?/)
args.unshift(chain.shift)
chain << [meth, args]
end
chain.first
end
def parse(chain)
meth, args = chain
return meth unless args.respond_to?(:[])
args[0] = parse(args[0]) if args[0].is_a?(Array)
"#{meth}(#{args.join(', ')})"
end
end
Code.new("'a,b' | split: ',' | first | upcase").process # upcase(first(split('a,b', ',')))
Code.new("'a' | link_to: 'www.terra.com.br'").process # link_to('a', 'www.terra.com.br')
Code.new("'b'").process # 'b'
Code.new("my_array | first | sum: 1").process # sum(first(my_array), 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment