Ruby on Rails Friday, August 31, 2012

On 31 August 2012 08:59, Joshua Baldock <lists@ruby-forum.com> wrote:
> Message column and example message looks like this:
>
> "The [user] is logged in via [hostname]"

I assume the square brackets are not in the string, so that a real
string might look like :

"The administrator is logged in via michael-desktop"
?

If so, you'll probably want to play with some string matching methods.
http://www.ruby-doc.org/core-1.9.3/String.html

"match" is a good place to start.

class MyModel < AR::Base
# my model has a big string field called "note_details", from
# which I want to extract the username and hostname values

def username
note_details.match(/The (\S*) is logged in via (\S*)/)[1]
end

def hostname
note_details.match(/The (\S*) is logged in via (\S*)/)[2]
end
end

in the view you can access @my_model.username and @my_model.hostname
like any other attributes. If you have any issue with performance, you
could memoize the results, so you only run the .match once.

HTH

--
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 rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment