How to use embedded ruby in ActionMailer subject - ruby-on-rails

I'm trying to use some embedded ruby in the subject line of an email coming from ActionMailer but keep getting different errors.
I couldn't find any documentation on the proper syntax. Any resources to fix this line of code?
mail(to: #user.email, subject: "Your Reservation Confirmation for" + #restaurant.name)
I've passed in all of the variables fine. I just need to see how I can combine text and these inputs.
Thanks

There are two common ways to it:
First:(regarding rep)
"...Confirmation for" + #restaurant.name.to_s
Second:
you can use string interpolation
"...Confirmation for #{#restaurant.name}"

I don't know whether this is intentional, but apparently #restaurant.name is returning a number (as you clarified, you're getting a TypeError: no implicit conversion of Fixnum into String). Calling #restaurant.name.to_s will solve that.
As G.B mentioned in another answer, string interpolation like "...Confirmation for #{#restaurant.name}" works too, since it calls #to_s for you automatically.
I'm putting the solution into an answer, since we found it while clarifying in the comments.

Related

Ruby symbol naming

I am currently reviewing a clients code base for the company I am interning for. The API is built with Ruby on Rails. I am new to Ruby, but have programmed in other languages, so looking through the code (and some tutorials), I have been able to understand most of what is going on, but there is a line that looks like the code below that is throwing me off. Why do the names of the symbols have equals in front? This feels illegal, but ruby is kinda cool. Thank you for your help.
delegate :name=, :description=, :tags=, to: :user
Another point: In Ruby, as a pattern you don't use the prefixes set or get, instead you use just the attribute name for the get and suffix = for the set. Example: setName and getName methods would be name= and name respectively.
Ruby allows you to use the setter method in these sintaxes: obj_instance.name = 'Name' (You can omit the () and use space before caracteres like =) or obj_instance.name=('Name').
A ruby symbol has very few restrictions concerning the characters it can have, and it's mainly linked to the "easy" representation we usually choose.
It's totally possible to have the following symbols:
:"hello/world"
:€
:"a+b"
It becomes a bit trickier when the symbol is used to represent a method, because we like the easy syntax that comes with it, but it's actually the same as sending the symbol using e.g. public_send:
foo.public_send(:"a+b")
This code will work if you define a method named :"a+b". Of course, you can't define it with the usual def, but it's still possible.
Now, some methods such as name= offer an additional semantic, so that the following are equivalent:
object.name = "Fubar"
object.send(:name=, "Fubar")

How do I fix: ArgumentError: invalid byte sequence in UTF-8?

I am getting this type of error in the logs :
Parameters: {"id"=>"4", "step"=>{"documents_attributes"=>{"0"=>
{"file"=>"\x89PNG\r\n\u001A\n\u0000\u0000\u0000\rIHDR\u0000\..."}}}}
def update
#step = Step.find_by(id: params[:id])
if #step.update(steps_params)
render :json => #step
else
render :json => { :responseStatus => 402,
:responseMessage => #step.errors.full_messages.first}
end
end
During update, it rollbacks without giving any error (not execute else condition)
ArgumentError (invalid byte sequence in UTF-8):
(0.2ms) ROLLBACK
How can I fix or handle this type of request?
Your question is how to handle this type of request or error. So here is my suggestion of a general strategy.
First, do your homework. You could easily find this past question, for example. If you have tried the way already but found it did not work, you should have described what you did and what did not work in your question.
Now, I am assuming you can reproduce the case or at least you can expect you will encounter the same problem in near future (or you can wait till then) so you will have a more chance to pin down the problem next time. If you know what parameters caused the error, I guess you can reproduce the case in your development environment. However, if not, it is more tricky to pin down — it heavily depends how much information about the error and input you have and what development environment you can use, and my answer does not cover the case.
The first objective should be to pin down which command (method) exactly in your code caused an error. Did it happen just inside Rails or did your DB raise an error?
In your specific case, did it occur at Step.find_by or #step.update or else? What is steps_params? It seems like a method you have defined. Are you sure steps_params is working as expected? (You may be sure, but we don't know…)
A convenient way to find it out is simply to insert logger.debug (or logger.error) etc before and after each sentence. In doing it, it is recommended to split a sentence into smaller units in some cases. For example, steps_params and update() should be separated, such as (in the simplest case),
logger.debug 'Before steps_params'
res_steps_params = steps_params
logger.debug 'Before update'
res_update = #step.update(res_steps_params)
logger.debug 'Before if'
if res_update
# ……
Obviously you can (and perhaps should) log more detailed information, such as, res_steps_params.inspect, and you may also enclose a part with a begin-rescue clause so that you can get the detailed infromation about the exception and log it. Also, I can recommend to split update into 2 parts – substitutions and save – to find out exactly what action and parameter cause a problem.
Once you have worked out which of DB or Rails or something before (like HTTP-server or Client-browser) is to blame and which parameter causes a problem, then you can proceed to the next stage. The error message suggests it is a character-encoding issue. Is the character encoding of a string invalid (as a UTF-8), or wrongly recognised by Rails (which might be not a fault of Rails but of the client), or not recognised correctly by the DB?
Wherever the problem lies, it is usually (though not always!) possible to fix or circumvent character-encoding problems with Ruby (Rails). The Ruby methods of String#encode, String#encoding, and String#force_encoding would be useful to diagnose and perhaps fix the problem.
As an added note, it can be useful, if possible in your environment, to browse the logfile of your DB (PostgreSQL?) to find out which query passed from Rails to the DB caused a problem (if a query was indeed passed to them!). Alternatively, Rails Gem SQL Query Tracker might be handy to know what queries your Rails app create (though I have never used it and so can't tell much.)
At the end of the day, when a code misbehaves mysteriously, I am afraid only the sure way to solve is to narrow down the problematic clause or parameter step by step. Good luck!

Disadantages of defining inspect on BigDecimal

I am using the decimal type in Rails for storing currency.
However, I am tired of constantly seeing results like:
nominal_amount: #<BigDecimal:7f919884b648,'0.7E6',9(18)>
When I use the Rails console.
I can fix this by defining inspect as def inspect; to_s; endon BigDecimal, but I am concerned that it could lead to peculiar bugs.
Anyone who can vouch for or warn against this monkey patch?
Ruby Doc suggests to override inspect for user defined classes. It returns a human readable string. No other code should rely on the functionality of inspect. So if you decide, that it is more human-readable - to you - if you change the default behavior it is okay. As long as you don't include it in a gem or other code foreign developers will use.
http://ruby-doc.org/core-2.1.1/Object.html#method-i-inspect
Hmm, if you put it in an initializer and run it in dev mode only... I don't see any risk. There is a chance someone else's code counts on BigDecimal.inspect returning an object string. I would say it's a development only modification.
inspect "Returns debugging information about the value as a string".
See apidock.com/ruby/BigDecimal/inspect
I doubt that overriding debugging output format can break anything. I'm monkey-patching it to to_s as well.

What is the use of _() in ruby/rails

I am looking at the source code of an program trying to figure out how it does certain things. One thing that caught my eye was the use of things like this in the views"
<%= _("Publish settings") %>
and in the controller:
flash[:notice] = _('Article was successfully created')
When I do _("Test") in the console it just returns "Test" string. So what is the use of the _() syntax. Haven't seen it before and can't find anything on google.
Any info will be appreciated.
It surely looks like some localization feature. As far as I can tell preferred method of doing that in Rails3 is t method, but if someone used external GetText gem for this purpose he might end up in such notation.

can't dup NilClass when using Sanitize gem

Alright this probably is the worst error I have found ever.
I have two projects, both using same code:
Sanitize.clean(string, Sanitize::Config::BASIC)
but one works and another fails.
Problem is similar to this poor guy's post: https://stackoverflow.com/questions/2724342/cant-dup-nilclass-how-to-trace-to-offender
Could anybody help please?
This will happen if you pass nil into clean() instead of a string. Make sure your string variable is really a string.

Resources