Formotion for
Rubymotion makes it a breeze to create views with forms.
I am building a rubymotion app and my login form uses formotion. I
needed to set background color for my form and here is how you can set a
background color to a form created using Formotion.
After the login view is done loading, I’m creating a new UIView and setting its background color.
Then this UIView object is set as the background view to formotion’s table view.
Setting header image
If you want to add some branding to the login form, you can add a image
to the form’s header by adding the below code to viewDidLoad:
We are creating a UIImageView and initializing it with the image we want to show in the header.
Now, set the tableview’s tableHeaderView value to the UIImageView we created.
If you generate a Rails application in 3.2 then ,by default, you will see a file
at config/initializers/session_store.rb . The contents of this
file is something like
Notice that towards the end unescaped_content has – .
That is a separation marker. The value before – is the real
payload. The value after – is digest of data.
So we are able to get the data that is stored in cookie. However we
can’t tamper with the cookie because if we change the cookie data then
the digest will not match.
Now let’s see how rails matches the digest.
In order to create the digest rails makes of use of
config/initializer/secret_token.rb . In my case the file has
following content.
Notice that the result of above produces a value that is same as
digest in earlier step. So if cookie data is tampered with then the
digest match will fail. This is why it is absolute necessary that
attacker should not be able to get access to secret_token
value.
Did you notice that we can access the cookie data without needing
secret_token. It means the data stored in cookie is not encrypted
and anyone can see it. That is why it is recommended that application
should not store any sensitive information in cookie .
Using cookie gives you more control
In the previous example we used session to store and retrieve
data from cookie. We can directly use cookie and that gives us a
little bit more control.
Using unsigned cookie
1
cookies[:github_username]='neerajdotname'
Now if we look at cookie stored in browser then this is what we see.
As you can see now we have two keys in our cookie. One created by
session and the other one created by code written above.
Another thing to note is that the data stored for key
github_username is not Base64encoded and it also does
not have – to separate the data from the digest. It means this
type of cookie data can be tampered with by the user and the Rails
application will not be able to detect that the data has been tampered
with.
Now let’s try to sign the cookie data to make it tamper proof.
1
cookies.signed[:twitter_username]='neerajdotname'
Now let’s look at cookies in browser.
This time we got data with another key twitter_username .
Another thing to notice is that cookie data is signed and is tamper
proof.
When we use session then behind the scene it uses
cookies.signed. That’s why we end up seeing signed data for key
_demo_session .
Tampering signed cookie
What happens when user tampers with signed cookie data.
Rails does not raise any exception. However when you try to access
cookie data then nil is returned because the data has been tampered
with.
Security should be on by default
session , by default, uses signed cookies which prevents any kind of
tampering of data but the data is still visible to users. It means we
can’t store sensitive information in session.
It would be nice if the session data is stored in encrypted format. And
that’s the topic of our next discussion.
Rails 4 stores session data in encrypted format
If you generate a Rails application in Rails 4 then ,by default, you will see a file
at config/initializers/session_store.rb . The contents of this
file is something like
In the above case we got the answer. But the answer is 400 instead of
4 . That is because the proc binding refers to the variable x. The
binding does not hold the value of the variable, it just holds the list
of variables available. In this case the value of x happens to be 20
when the code was executed and the result is 400 .
x does not have to a variable. It could be a method. Check this out.
In the above case x is a method definition. Notice that binding is
smart enough to figure out that since no x variable is present let’s
try and see if there is a method by name x .
In the above case the value of x is set as 20 at the code
compile time. Don’t get fooled by x being 2 inside the method call.
Inside the method call a new scope starts and the x inside the method
is not the same x as outside .
Issues because of lexical scoping
Here is a simple case.
12345678910111213
classPersoncode=proc{putsself}define_method:namedocode.call()endendclassDeveloper<PersonendPerson.new.name# => PersonDeveloper.new.name# => Person
In the above case when Developer.new.name is executed then output is
Person. And that can cause problem. For example in Ruby on Rails at a
number of places self is used to determine if the model that is being
acted upon is STI or not. If the model is STI then for Developer
the query will have an extra where clause like
AND "people"."type" IN ('Developer') . So we need to find a solution
so that self reports correctly for both Person and ‘Developer` .
instance_eval can change self
instance_eval
can be used to change self. Here is refactored code using instance_eval .
Above code produces right result. However instance_eval has one
limitation. It does not accept arguments. Let’s change the proc to
accept some arguments to test this theory out.
123456789101112131415
classPersoncode=proc{|greetings|putsgreetings;putsself}define_method:namedoself.class.instance_eval'Good morning',&codeendendclassDeveloper<PersonendPerson.new.nameDeveloper.new.name#=> wrong number of arguments (1 for 0) (ArgumentError)
In the above case we get an error. That’s because instance_eval does
not accept arguments.
This is where instance_exec comes to rescue. It allows us to change
self and it can also accept arguments.
instance_exec to rescue
Here is code refactored to use instance_exec .
12345678910111213
classPersoncode=proc{|greetings|putsgreetings;putsself}define_method:namedoself.class.instance_exec'Good morning',&codeendendclassDeveloper<PersonendPerson.new.name#=> Good morning PersonDeveloper.new.name#=> Good morning Developer
As you can see in the above code instance_exec reports correct self
and the proc can also accept arguments .
Conclusion
I hope this article helps you understand why instance_exec is useful.
I scanned RubyOnRails source code and
found around 26 usages of instance_exec . Look at the usage of
instance_exec usage there to gain more understanding on this topic.
Let’s say that the route defintion looks like this.
1
/page/:id(/:action)(.:format)
The task at hand is to develop a new programming language which will
understand the rules of the route definitions. Since this language deals
with routes let’s call this language Poutes . Well
Pout sounds better so let’s roll with that.
It all begins with scanner
rexical is a gem which
generates
scanner generator. Notice that rexical is not a scanner itself.
It will generate a scanner for the given rules. Let’s give it a try.
Create a folder called pout_language and in that folder create
a file called pout_scanner.rex . Notice that the extension of the file
is .rex .
12
class PoutScanner
end
Before we proceed any further, let’s compile to make sure it works.
1234
$ gem install rexical
$ rex pout_scanner.rex -o pout_scanner.rb
$ ls
pout_scanner.rb pout_scanner.rex
While doing gem install do not do gem install rex . We are
intalling gem called rexical not rex .
Time to add rules
Now it’s time to add rules to our pout.rex file.
Let’s try to develop scanner which can detect difference between
integers and strings .
12345
class PoutScanner
rule
\d+ { puts "Detected number" }
[a-zA-Z]+ { puts "Detected string" }
end
Regenerate the scanner .
1
$ rex pout_scanner.rex -o pout_scanner.rb
Now let’s put the scanner to test . Let’s create pout.rb .
So the scanner is rightly identifying string vs integer. We are going to
add a lot more testing so let’s create a test file so that we do not have to
keep changing the pout.rb file.
Also let’s change the pout_scanner.rex file to return an array
instead of puts statements . The array contains information
about what type of element it is and the value .
Now that we have some background on how scanning works let’s get back to
business at hand. The task is to properly parse a routing statement like
/page/:id(/:action)(.:format) .
test for slash
The simplest route is one with / . Let’s write a test and then
rule for it.
Here we used rex to generate the scanner. Now take a look that
the pout_scanner.rb . Here is that
file . Please take a look at this file
and study the code. It is only 91 lines of code.
If you look at the code it is clear that scanning is not that hard. You
can handroll it without using a tool like rex . And that’s
exactly what Aaron Patternson did in
Journey . He handrolled the
scanner
.
Conclusion
In this blog we saw how to use rex to build the scanner to read
our routing statements . In the next blog we’ll see how to parse the
routing statement and how to find the matching routing statement for a
given url .
In the above case there are five different routing statements. Rails
needs to store all those routes in a manner such that later when url is
‘/photos/5’ then it should be able to find the right route statement that should
handle the request.
In this article we are going to take a peek at how Rails handles the
whole routing business.
Normalization in action
In order to compare various routing statements first all the routing
statements need to be normalized to a standard format so that one can
easily compare one route statement with another route statement.
Before we take a deep dive into how the normalization works lets first
see some normalizations in action.
After the normalization process the above routing statement is
transformeed into five different variables. The values for all those
five varibles is shown below.
app is the application that will be executed if conditions are
met. conditions are the conditions. Pay attention to
:path_info in conditions. This is used by Rails to
determine the right route statement. defaults are defaults
and requirements are the constraints.
In this case I omitted requirements and anchor for
brevity .
Notice that a single routing statement resources :users created
eight normalized routing statements. It means that resources
statement is basically a short cut for defining all those eight routing
statements .
So now that we have normalized the routing definitions the task at hand
is to find the right route definition for the given url along with
request_method.
For example if the requested page is /pictures/A12345 then the
matching routing definition should be get ‘pictures/:id’ =>
‘pictures#show’, :constraints => { :id => /[A-Z]\d{5}/ } .
In order to accomplish that I would do something like this.
I would convert all path info into a regular experssion and I would push
that regular expression in an array. So in this case I would have 12
regular expressions in the array and for the given url I would try to
match one by one.
This strategy will work and this is how Rails worked all the way upto
Rails 3.1 .
Aaron Patterson loves computer science
Aaron Patterson noticed that finding the best matching route definition
for a given url is nothing else but pattern matching task. And computer
science solved this problem much more elegantly and this happens to run
faster also by building an AST and walking over it.
So he decided to make a mini language out of the route
definitions . After all the route definitions , we write , follow certain
rules.
Following code was tested with edge rails (rails4) .
In a RubyonRails application we save records often. It is one
of the most used methods in ActiveRecord. In the blog we are going to
take a look at the lifecycle of save operation.
ActiveRecord::Base
A typical model looks like this.
12
classArticle<ActiveRecord::Baseend
Now lets look at ActiveRecord::Base class in its entirety.
Together methods rollback_active_record_state! and
with_transaction_returning_status ensure that all the
operations happening inside save is happening in a single
transaction.
Why save method needs to be in a transaction .
A model can define a number of callbacks including after_save
and before_save. All those callbacks are operated within a
transaction. It means if an after_save callback operation
raises an exception then the save operation is rolledback.
Not only that a number of associations like has_many and
belongs_to use callbacks to handle association manipulation.
In order to ensure the integrity of the operation the save operation is
wrapped in a transaction .
reverse order of operation
In the Base class the modules are included in the following order.
All the four modules have save method. The way ruby works the
last module to be included gets to act of the method first. So the order
in which save method gets execute is
Transactions,
AttributeMethods, Validations and Persistence
.
To get a visual feel, I added a puts inside each of the save
methods. Here is the result.
7 % of 200 should be 14. But float is returning
14.000000000000002 .
In order to ensure that calculation is right make sure that all the
actors participating in calculation is of calss
BigDecimal
. Here is how same operation can be performed using BigDecimal .
Above method works but I like to delegate the functionality of making
money out of a complex BigDecimal value to gem like
money . In this project we are using
activemerchant which depends
on money gem . So we get money gem for free. You might have to add money
gem to Gemfile if you want to use following technique.
money gem lets you get a money instance out of BigDecimal.
If you are doing any sort of calculation then all participating elements
must be either BigDecimal or Money instance. It is best if all the
elements are of the same type.
Ruby allows many different ways to execute a command or a sub-process. In this
article we are going to see some of them.
backtick
backtick
returns the standard output of the operation.
12
output = `ls`
puts "output is #{output}"
Result of above code is
123
$rubymain.rboutputislab.rbmain.rb
Note that backtick operation forks the master process and the operation
is executed in a new process. However this is a blocking operation. The
main application waits until the result of backtick operation completes.
If there is an exception in the sub-process then that exception is given
to the main process and the main process might terminate if exception is
not handled.
In the following case I am executing xxxxx which is not a valid
executable name.
12
outut=`xxxxxxx`puts"output is #{output}"
Result of above code is given below. Notice that puts was never
executed because the backtick operation raised exception.
123
$rubymain.rbmain.rb:1:in``': No such file or directory - xxxxxxx (Errno::ENOENT) from main.rb:1:in `<main>'
To check the status of the backtick operation you can execute $?.success?
123
output=`ls`puts"output is #{output}"puts$?.success?
Notice that the last line of the result contains true because
the backtick operation was a success.
1234
$rubymain.rboutputislab.rbmain.rbtrue
backtick returns STDOUT. backtick does not capture STDERR . If you want
to learn about STDERR then checkout this excellent article .
You can redirect STDERR to STDOUT if you want to
capture STDERR using backtick.
1
output=`grep hosts /private/etc/* 2>&1`
%x does the same thing as backtick. It allows you to have
different delimeter.
12
output=%x[ ls ]output=%x{ ls }
backtick runs the command via shell. So shell features like string
interpolation and wild card can be used. Here is an example.
system behaves a
bit like backtick operation. However there are some differences.
First let’s look at similarities.
Just like backtick, system is a blocking operation. You can
get the result of the operation using $?.success? .
system operations are also executed in a subshell.
Now the differneces between backtick and system .
system eats up all the exceptions. So the main operation never
needs to worry about capturing an exception raised from the child
process.
12
output=system('xxxxxxx')puts"output is #{output}"
Result of the above operation is given below. Notice that even when
exception is raised the main program completes and the output is printed. The value of output is nil because the child process raised an exception.
12
$rubymain.rboutputis
Another difference is that system returns true if the command was successfully performed ( exit status zero ) . It returns false for non zero exit status. Returns nil if command execution fails.
exec
exec
replaces the current process by running the external command. Let’s see
an example.
Here I am in irb and I am going to execute exec('ls').
I see the result but since the irb process was replaced by the exec process I am no longer in irb .
Behind the scene both system and backtick operations
use fork to fork the current process and then they execute the
given operation using exec .
Since exec replaces the current process it does not return
anything if the operation is a success. If the operation fails then
SystemCallError is raised.
sh
sh actually calls
system under the hood. However it is worth a mention here. This method is added by FileUtils in rake. It allows an easy way to check the exit status of the command.
The important thing to note here is that when I execute the program
ruby lab.rb I do not see any output on my terminal for first 10
seconds. Then I see the whole output as one single dump.
The other thing to note is that heroku is writing all this output to
stderr and not to stdout .
Above solution works but it has one major drawback. The push to heroku
might take 10 to 20 seconds and for this period we do not get any
feedback on the terminal. In reality when we execute git push heroku
master we start seeing result on our terminal one by one as heroku
is processing things.
So we should capture the output from heroku as it is being streamed
rather than dumping the whole output as one single chunk of string at
the end of processing.
If you are using heroku and if you have enabled https then site must be
redirected to use www . It means all Rails applications should
ensure that “no-www” urls are redirected to “www”.
In Rails3 it is pretty easy to do. Here is how it can be done.
Solr is an open source search platform
from Apache. It has a very powerful full-text search capability among
other things.
Solr is written in Java. And it runs as a standalone search server
within a servlet container like Tomcat. When you are working on a Ruby
on Rails application you do not want to maintain Tomcat server. This is
where websolr comes in picture. Websolr manages
the index and the Rails application interacts with index using a gem
called sunspot-rails .
The way sunspot works is that after every single web request it updates
solr about the changes that took place in the request. This is not
desirable. To turn that off add auto_commit_after_request
option to false in the config/sunsunspot.yml file.
I would also change the log_level for development to
DEBUG . The revised config/sunspot.yml file would look
like
In the above case anytime I create, update or destroy a product then as
part of after_save callback solr commit commands are issued.
Since after_save callbacks are part of ActiveRecord
transaction, this slows up the create, update and destroy operation. I
like all these operations to happen in background.
In the above case I used Delayed Job but you can use any background job processing tool.
In case of Delayed Job the higher the priority value the less is the
priority. By bumping the priority value to 50, I’m making sure that
emails and other background jobs are processed before solr work is taken
up.
Problem with remove_from_index
In the above case the call to remove_from_index has been
deferred to Delayed Job. However the record has already been destroyed.
So when Delayed Job takes up the work it first tries to retrieve the
record. However the record is missing and the background job fails.
From the websolr documentation it was not clear that the
sunspot gem first looks for an environment variable called
WEBSOLR_URL and if that envrionment variable has a value then
sunspot assumes that the solr index is at that url. If no value is found
then it assumes that it is dealing with local solr instance.
So if you are using websolr then make sure that your application has
environment variable WEBSOLR_URL properly configured in
staging and in production environment.