Rails helper method to display email with sub mask asterisk - ruby-on-rails-3

How to write like a helper method for email address to display with sub mask asterisk.
If user email address is like "john.a#stackoverflow.com", But in view I want to display joh***#***.com
<%= sub_masked_email("john.a#stackoverflow.com") %>
##joh***#***.com

So you can write a helper method which can be reused multiple time by calling it on any string. Here is what I came up with below:
helper_method
def sub_masked_email(string)
string.gsub(/(?<=.{2}).*#.*(?=\S{2})/, '****#****')
end
calling it on any string
sub_masked_email("john.a#stackoverflow.com")
output
"jo*****#****om"
So this method shows the first two letters and shows the last two letters and replaces all other text with ****#****
Just a pointer to what you need and can still be better than this.

Related

rails user input with <script>, stored, and displayed

I have an application that collect user input and store to DB and show back to user.
One user entered "alert(1)" into the name field and saved it into DB.
Whenever the name is displayed, the page will be broken.
I know how to fix that input only with validation for input, and h() for output.
However, I have so many input fields and so many outputs that accept users' text.
Is there any simple way to prevent this happening(i.e. overriding params method, etc)?
I also want to know how you expert guys are dealing with this problem?
As of Rails 3, my understanding was that embedded ruby code was html escaped by default. You don't need to use h() to make it that way. That is, if you use <%= "<script>a=1/0;</script>" %> in a view, the string is going to be made html safe, and so the script doesn't execute. You would have to specifically use raw() or something similar to avoid it - which you should naturally not do unless you're really confident about the contents.
For output, Rails 3 automatically html-encode all text unless I use raw() method.
For input, How about making a common validator and apply to all fields that are text or string? Is it desirable?
http://api.rubyonrails.org/classes/ActiveModel/Validator.html
class MyValidator < ActiveModel::Validator
def validate(record)
record.class.columns.each do |c|
if c.type==:text || c.type == :string
record.errors.add c.type, "script tag is not allowed" if c[/<script[^>]*>/]
end
end
end
end

Load object from model on every page?

I'm looking to load a single (chosen randomly) object from a single table in my database on every page of my rails app.
For example, a quotes table which has several quotes in the table, and I just want one on every page load.
What's the best way to accomplish this? Obviously copy & pasting the query into each controller isn't the right way to go about this.
I wouldn't use before_filter for this, there is no need to access database on redirecting actions and other "not rendered" actions. Instead I would use helper_function, and I would call it in the layout, as you need to position it anyways.
def random_quote
#quote ||= "Select random quote here"
end
helper_method :random_quote
Your method of selecting a quote is up to you. You just need to access random_quote as a normal helper method in the layout. This only access one quote per action, only if the layout is rendered.
This kind of stuff typically goes into a before_filter in the ApplicationController :
before_filter :get_random_quote
#This code is executed before every action of your app
def get_random_quote
random_id = ...#Generate a random ID ...
#random_quote = Quote.find(random_id)
end
Then in your views, just refer to #random_quote. Done!
Edit : on second thought, Matzi solution seems smarter. The request will only get called when you actually output something. Nothing's wasted.
Assuming PostgreSQL:
before_filter :get_quote
def get_quote
#quote = Quote.order('RANDOM()').limit(1)
end

Rails ActiveRecord hash displayed on page

I am creating a sortable list of items from my database using the railscast found here: http://railscasts.com/episodes/228-sortable-table-columns
The sorting works fine, but when the page displays, it seems to print out some sort of hash above the table according to the number items. Each unit looks something like this:
#<ActiveRecord::Relation:0x00000006f9a500>
I've checked the html code and there is nothing in it that prints anything. Is this some sort of debug statement? How do I get it to stop printing?
You are printing object, but you need only one attribute.
Do something like this:
<%= your_object.YOUT_ATTRIBUTE %>

Rails 3.1: UrlEncode issues with periods (.)

I have a site where when a user searches for an artist, song or album and click search, the search results are displayed. The individual search terms are then set to be clickable, meaning each use their own paths (or routes) to generate links.
The issue I keep running into is with random weird characters showing up in some of the artists, songs or album names (such as periods (.)). Is there anyway to url encode these?
Here is my current code:
<% artists[0..5].each do |art| %>
<li><span><strong><%= link_to "#{art}", artist_path(CGI::escape(art)) %></strong></span></li>
<% end %>
Assume you have an album name called "slash#^[]/=hi?qqq=123"
encoded = URI.escape str_to_be_encoded
encoded = URI.escape(str_to_be_encoded, Regexp.new("[^#{URI::PATTERN::UNRESERVED.gsub('.','')}]"))
The first one would encode to
"slash#%5E[]/=hi?qqq=123"
The second would encode to
"slash%40%5E%5B%5D%2F%3Dhi%3Fqqq%3D123"
What happens is that most url encoding methods would not escape characters that it thinks it part of a value url, so symbols like equal and question mark are not escaped.
The second method tells the escape function to also escape url-legal characters. So you get a better encoded string.
You can then append it to your url like
"http://localhost:3000/albums/1-#{encoded}"
Hope this helps.

Best way to hook into a Rails 3 page lifecycle

I have the following scenario: I am adapting a edit in place library to be able to display formatted values after the value is edited on an input field.
For that, I want to store the id for some fields being rendered on a given controller action to be served via AJAX whenever needed.
I want to be able to do the following in a view:
<%= edit_in_place #object, :attribute do |value|
"Formatted display value is #{value}"
end
%>
So, I generate a UUID for the control being rendered:
<input ... data-uuid="27b52850-d68f-012e-5dc8-28373723e63c" ...>
The ultimate goal is to keep a FormattingRules hash that would take the block being passed and assign it to the UUID so I could later on, after the user has edited the value, call an AJAX method to format the value:
http://server/format/27b52850-d68f-012e-5dc8-28373723e63c?value=My+Value
The following code is triggered:
def show
block = BestInPlace::FormattingRules[params[:id]]
render :text => block.call(params[:value])
end
And the cod returns:
Formatted display value is My Value
Which is great. With this, I can hide the edit in place input and display the formatted value.
Everything works already, however the FormattingRules hash is growing indefinitely and never being emptied.
My question is: is there a way I can hook into the Rails lifecycle and make this hash more granular (per page or session, maybe?) and make sure it's gone after the page is no longer being used?