Initializing Custom YML Configuration Variables for Different Environments in Rails

Another common problem that rails developers face while developing web applications that connect to multiple external systems and api’s is configuring the the same parameters for different environments.

The simplest way -

  • Add a folder to the config folder of your application

  • Add all the configuration in as a yml file, like how we use the database.yml with all the environments in it

sample file: config/google_api.yml

1
2
3
4
5
6
7
8
9
10
development: &default_settings
  google_analytics_id: 'UA-xxxxxxxx-1'
test:
  <<: *default_settings
sandbox:
  google_analytics_id: 'UA-xxxxxxxx-2'
staging:
  google_analytics_id: 'UA-xxxxxxxx-3'
production:
  google_analytics_id: 'UA-xxxxxxxx-4'

the &default_settings and *default_settings can be used to pass the same values into another yml

  • add the following to your rb file:

    File: config/environment.rb

1
2
3
4
5
6
7
8
9
10
11
# Load the rails application
require File.expand_path('../application', __FILE__)

# Auto Load APP_CONFIG for the corresponding environment configuration
APP_CONFIG = HashWithIndifferentAccess.new
load_files = Dir["#{Rails.root}/config/app_config/*.yml"].each do |file|
  APP_CONFIG.merge!(YAML.load_file(file)[Rails.env])
end

# Initialize the rails application
Livegamer::Application.initialize!

The above code adds all the yml files inside the folder we created(app_config) under the config folder to a hash(APP_CONFIG).

  • Now we can use get the google analytics id with the following
1
google_id = APP_CONFIG['google_analytics_id']

This would return the corresponding configuration variable depending upon the environment.

Simple.. :)

Any questions on this, please feel free to ask. We’re here to help…

Extend vs Include in Ruby Module

Extend vs. Include Modules are used for mixins, ruby’s way of handling muliple inheritance without the complications. There are two ways to mixin, either include or extend to mix in a module’s functionality into a class.

Difference:

include makes the module’s methods available to the instance of a class, attached to the instances of the class alone.

1
2
3
4
5
6
7
8
9
10
11
12
module Foo
  def foo
    puts 'heyyyyoooo!'
  end
end

class Bar
  include Foo
end

Bar.new.foo # heyyyyoooo!
Bar.foo # NoMethodError: undefined method ‘foo’ for Bar:Class

extend makes these methods available to the class as class methods, implemented with a self << class*

1
2
3
4
5
6
class Baz
  extend Foo
end

Baz.foo # heyyyyoooo!
Baz.new.foo # NoMethodError: undefined method ‘foo’ for #\<Baz:0x1e708>

More information here at the source link.

Any questions on this, please feel free to ask. We’re here to help…

Comments

Ruby Comparison Operators

There has been lots of questions on the comparison operators. So we yanked it for you..

OperatorDescriptionExample
== Checks if the value of two operands are equal or not, if yes then condition becomes true. (a == b) is not true.
!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (a != b) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (a > b) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (a < b) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (a >= b) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (a <= b) is true.
<=> Combined comparison operator. Returns 0 if first operand equals second, 1 if first operand is greater than the second and -1 if first operand is less than the second. (a <=> b) returns -1.
=== Used to test equality within a when clause of a case statement. (1…10) === 5 returns true.
.eql?True if the receiver and argument have both the same type and equal values. 1 == 1.0 returns true, but 1.eql?(1.0) is false.
equal?True if the receiver and argument have the same object id. 1 == 1.0 returns true, but 1.eql?(1.0) is false.

There’s more here at the Source Link

Any questions on this, please feel free to ask. We’re here to help…

Working With Processes in Unix

There are two commands heavily used by developers for checking their pocesses in unix.

  1. Firstly it is the search for processes
1
ps -ef | grep search_process

or

1
ps aux | grep search_process

what’s the difference, well both do the same task

link

Both list all processes of all users. In that aspect -e and ax are completely equivalent. Where they differ is output format specifier, -f is “full”, while u is “user-oriented”. The displayed columns are different: columns for ps -f UID PID PPID C STIME TTY TIME CMD

columns for ps u USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND

The difference between ps -ef and ps aux is due to historical divergences between POSIX and BSD systems. At the beginning, POSIX accepted the -ef while the BSD accepted only the aux form.

  1. Secondly to kill the process that we just found
1
kill -9 pid

or

1
kill -SIGKILL PID

or if we know the process name and if the unix system supports

1
killall nginx

Tip: What if we need to kill all the processes that starts with ‘schedule’. Here it is..

1
ps aux | grep schedule | grep -v grep | awk '{print $2}' | xargs kill -9

A quick description of the steps:

  1. “ps aux | grep schedule” searches for the processes by the name schedule and returns the rows
  2. “grep -v grep” excludes grep from the searched process list (rows)
  3. “awk ‘{print $2}’” prints the second column of all the values returned. Which is mostly the process Id, if not choose the corresponding column by its number of appearance in the rows returned
  4. “xargs kill -9” sends the kill signal to all the selected process Ids

Please make sure that you are searching for the right processes before killing them.

Any questions on this, please feel free to ask. We’re here to help…

aux, ps, unix
Comments

Setting Up a Development Mailer for Rails With a Gmail Account

Setting up the rails mailer for development purposes is much easier. using the action mailer to configure the gmail services, is just a few commands and configurations away…

Make sure that these settings are not used in production.

  1. Firstly Sign Up for a dummy gmail account.
  2. Next add the following configuration in development.rb

File: config/environments/development.rb

1
2
3
4
5
6
7
8
9
10
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  :address              => "smtp.gmail.com",
  :port                 => 587,
  :domain               => '<your_domain>',
  :user_name            => '<user_name>',
  :password             => '<password>',
  :authentication       => 'plain',
  :enable_starttls_auto => true  }

Login to the gmail account and check the sent mails, to preview the sent mail.

There’s a lot more that can be done with this, check the Rails Guids for more information.

Any questions on this, please feel free to ask. We’re here to help…

Using Screen to Keep Unix Sessions Active

In Unix, what is screen, and how do I use it?

The screen program allows you to use multiple windows (virtual VT100 terminals) in Unix.

Note: UITS does not support screen.

Features

  1. If your local computer crashes, or you are connected via a modem and lose the connection, the processes or login sessions you establish through screen don’t go away. You can resume your screen sessions with the following command:
1
  screen -r

In some cases you may have to manually “detach” your screen session before resuming it. For more information, see the Knowledge Base document Using screen, why can’t I re-attach to my session after a lost connection?

  1. The screen program creates multiple processes instead of multiple Unix login sessions, which means that it is resource-efficient.

  2. You can cut and paste between different screens without using a mouse. Thus, you don’t need to be on a computer with a windowing environment such as Mac OS, Mac OS X, Windows, or the X Window System.

  3. It has a block copy feature which is similar to the kill rectangle feature of Emacs.

  4. You can copy and paste more than one page at a time, which you cannot do with some clients. You can scroll up more than one page, depending on how many scrolling lines you have set with the -h option.

  5. Using the detach feature, you can save screen processes when logging out and resume where you left off, saving the trouble of restarting them.

Starting screen

To start screen, enter the following command:

1
  screen

General commands

Note: Every screen command begins with Ctrl-a .

Ctrl-a c Create new window (shell)
Ctrl-a k Kill the current window
Ctrl-a w List all windows (the current window is marked with “*”)
Ctrl-a 0-9 Go to a window numbered 0-9
Ctrl-a n Go to the next window
Ctrl-a Ctrl-a Toggle between the current and previous window
Ctrl-a [ Start copy mode
Ctrl-a ] Paste copied text
Ctrl-a ? Help (display a list of commands)
Ctrl-a Ctrl-\ Quit screen
Ctrl-a D (Shift-d) Power detach and logout
Ctrl-a d Detach but keep shell window open

Press the Spacebar or Enter to end a command.

To copy a block

To get into copy mode, press Ctrl-a [ .

To move the cursor, press the h , j , k , and l (the letter l) keys. The 0 (the number 0) or ^ (the caret) moves to the start of the line and $ (the dollar sign) moves to the end of the line. Ctrl-b scrolls the cursor back one page and Ctrl-f scrolls forward one page. To set the left and right margins of copy, press c and C (Shift-c). The Spacebar starts selecting the text and ends selecting the text. To abort copy mode, press Ctrl-g .

To paste a block

To paste the copied text to the current window (as many times as you want), press Ctrl-a ] .

Other commands

To run a program or execute any Unix command in a new window, at the Unix prompt, enter:

1
  screen unixcommand

Above, replace unixcommand with the appropriate command name.

To automatically start several windows when you run screen, create a .screenrc file in your home directory and put screen commands in it.

To quit screen (kill all windows in the current session), press Ctrl-a Ctrl-\ .

The man pages for screen are quite readable and make a good tutorial. At the Unix prompt, enter:

1
  man screen

[Source Link][http://kb.iu.edu/data/acuy.html]

If your unix server does not support screen. It is always a better to run some commands with nohup.

Any questions on this, please feel free to ask. We’re here to help…

Comments

Using Nohup to Prevent Processes Stopping on Disconnect

nohup is an unix command which prevents “hangups on logout” which also means that if you decide you need to logoff the from the session with the server, the command will continue to run as the user.

Syntax:

1
nohup run_command &

run_command in the above Syntax is the name of the command you want to run.

And the & at the end of the line makes the process run in the background. Once the command starts you can then continue to issue other commands or logout if you choose so. After executing the above command you’ll see this displayed on the command line, and you may need to press the key before being able to enter other commands.

This means that all the output from the command will go into a file called “nohup.out” in the current working directory. You can tail the same to check the logs.

1
tail -f nohup.out

Also we can alternatively output the text from the command to a different file using redirection.

1
nohup run_command > run_command.log &

If your unix server supports screen. It is always a better option with more features.

Any questions on this, please feel free to ask. We’re here to help…

Comments

Understanding Ruby Object Model

  1. classes store methods

  2. objects store instance variables

ruby method lookup flow

Any questions on this, please feel free to ask. We’re here to help…

Comments

Binding Pry to Rails Console

Add the following lines to make the rails console to use pry. make sure that

File: Gemfile

1
gem 'pry'

File: config/environments/development.rb

1
2
3
4
silence_warnings do
  require 'pry'
  IRB = Pry
end

Any questions on this, please feel free to ask. We’re here to help…

Comments

Cases and Switches in Ruby

One of the common questions that we get about people coming from other programing languages is with the way switch cases work in ruby.

The case..switch works like a ‘===’ operator and not like a ‘==’ operator. Here are a few examples of how it work. Here are a few examples of how it works.

Syntax:

1
2
3
4
5
6
7
8
case value_returning_argument
when case_1
  case_statement_list_1
when case_2
  case_statement_2
else
  case_statement_else
end

Example 1:

A simple example would be:

1
2
3
4
5
6
7
8
9
10
11
puts "Enter some value: "
some_value = gets.chomp

case some_string
when 'some', 'other'
  puts 'Entered some other value'
when 'no'
  puts 'Entered no value'
else
  puts 'Why did you enter that value??'
end

Example 2:

Here’s an example that accepts regular expression

1
2
3
4
5
6
7
8
9
10
print "Enter a value: "
some_string = gets.chomp
string_type = case
  when some_value.match(/^\d+$/)
    'Number'
  when some_value.match(/^[a-zA-Z]+$/)
    'String without Numbers'
  else
    'Some text'
  end

Example 3:

Here’s an example that works with a range

1
2
3
4
5
6
7
8
case some_string
when 1..5
  puts "Between 1 and 5"
when 6..8
  puts "Between 6 and 8"
when 9
  puts "Entered 9"
end

Example 4:

The parameter for case is optional

1
2
3
4
5
6
7
8
case
when some_string=='hi'
  puts "you just said hi"
when some_string=='there'
  puts "you just said there"
else
  puts "whatever..!"
end

Any questions on this, please feel free to ask. We’re here to help…