Frederick Cheung wrote:
> On 16 Oct 2008, at 08:36, David Trasbo wrote:
>
>> partial
>> and a space. My problem is that the method only supports values that
>> matches \w+. I would like values to be able to match .* or .+.
>>
> Greedy things like .* are almost always dangerous as they make you
> consume the entire string. typically you'd want to scan or scan_until
> the first occurence of something
Yes.
> the following modification to the previous solution does that:
>
> def dropify(content)
> s = StringScanner.new(content)
> output = ""
> previous_end = 0
> while s.scan_until(/\{/)
> output << content[previous_end, s.pointer - previous_end - 1]
> partial = s.scan(/\w+/)
> s.skip /\s+/
> arguments = {}
> while label= s.scan(/(\w+):"/)
> name=s[1]
> value = s.scan /[^"]+/
> arguments[name.to_sym] = value
> s.skip /"\s+/
> end
> s.skip_until /\}/
> previous_end = s.pointer
> puts arguments.inspect
> end
> end
This works perfectly. I modified it a little bit for my needs. This
method supports multiple arguments with values containing any kind of
characters:
def dropify(content)
s = StringScanner.new(content)
output = ""
previous_end = 0
while s.scan_until(/\{/)
output << content[previous_end, s.pointer - previous_end - 1]
partial = s.scan(/\w+/)
s.skip /\s+/
arguments = {}
while label= s.scan(/(\w+):"/)
name = s[1]
value = s.scan /[^"]+/
arguments[name.to_sym] = value
s.skip /"\s+/
end
s.skip_until /\}/
previous_end = s.pointer
output << render(:partial => "drops/#{partial}", :locals =>
arguments)
end
output << content[s.pointer, content.length - s.pointer]
end
> Having scanned \w+:" (ie a label and the opening quote mark) we
> consume all non " characters and says those are the arguments. then we
> skip over the closing " and any whitespace
>
> dropify('{test_partial foo:"bar foo" bar:"foo bar"}')
>
> outputs
>
> {:foo=>"bar foo", :bar=>"foo bar"}
Great! Thanks again for your help, Fred.
David T.
--
Posted via http://www.ruby-forum.com/.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---