Indyarocks

Happy Hacking!

Rack Basics

| Comments

Today I explored Rack, an awesome API connecting web servers and web frameworks by Christian Neukirchen. Here is an introduction article by Christian Neukirchen.

Rack was insipired from python’s WSGI.

What is Rack?

To put in the words of Christian,

Rack provides a minimal, modular and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in the simplest way possible, it unifies and distills the API for web servers, web frameworks, and software in between (the so-called middleware) into a single method call.

Instead of going deeper in documentation, I’ll walk through what exactly Rack is, and how it fits in different web-frameworks in Ruby. I’ve put the references at the end of the post, which helped me understand Rack.

ActiveRecord Logger in Rails Console

| Comments

This came to my surprise, as I was going through ‘The Rails 4 Way’ by Obie Fernandez, that we can have our own logger instances in Rails.

Watch, what ActiveRecord is doing with your query in console itself. :)

I came across blog of Jamis Buck, and he had given on more interesting piece of hack to see the log in console. In your config/environment.rb define following method:

1
2
3
4
def log_to(stream)
  ActiveRecord::Base.logger = Logger.new(stream)
  ActiveRecrod::Base.clear_active_connections!
end

Now you can buffer your logs in a local variable.

1
2
3
4
5
6
7
8
9
10
11
12
13
> log_to STDOUT
=> ..
> Post.find(:first)
  Post Load (0.000138)   SELECT * FROM posts LIMIT 1
=> #<Post:0x1234 ...>
> buffer = StringIO.new
=> ..
> log_to buffer
=> ..
User.first(:first)
=> #<User:0x1234...>
> p buffer.string
=> "\e...." # Logs here

This can be found useful at many place you want to check the behavior of certain queries in console.

Thanks Jamis/Obie :)

Using Ruby Gsub With a Hash

| Comments

Gsub with Hash We all have used gsub for global substitution of a pattern in string. The cool thing I came across today is, you can use hash to define the replacement.

1
2
3
4
5
6
7
8
9
10
11
def cool_gsub_with_hash(str)
  str.gsub(/[aeiou]/, 'a' => '1', 'e' => '2', 'i' => '3', 'o' => '4', 'u' => '5')
end

> cool_gsub_with_hash("We all have used gsub for global substitution of a pattern in string. ")

 => "W2 1ll h1v2 5s2d gs5b f4r gl4b1l s5bst3t5t34n 4f 1 p1tt2rn 3n str3ng. "

> cool_gsub_with_hash("hello")

 => "h2ll4"

Here we are not restricted with single character replacements:

1
2
3
4
5
6
7
8
def gsub_word_with_hash(str)
  str.gsub(/H(ello)?i?/, 'Hi' => "Namaste", "Hello" => "Wannakam")
end

> gsub_word_with_hash("Hello Chandan")
 => "Wannakam Chandan"
> gsub_word_with_hash("Hi Chandan")
 => "Namaste Chandan"

I found it quite interesting. Courtesy: Bozahidar