Created
July 19, 2012 13:47
-
-
Save rafaelss/3144043 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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