Showing posts with label Rails. Show all posts
Showing posts with label Rails. Show all posts

Monday, July 13, 2015

[PostgreSQL] List index usage

Update: This query is much cooler Index size/usage statistics

--

In psql console, connect to the database you want to check its indexes usage. Then execute this query.
# SELECT * FROM pg_stat_user_indexes ORDER BY idx_scan DESC;
If your database is manage by Rails's schema, you could filter out auto generated public key indexes like so
# SELECT * FROM pg_stat_user_indexes WHERE indexrelname NOT LIKE '%_pkey' ORDER BY idx_scan DESC; 

Tuesday, January 28, 2014

Rails4's Active Record where not nil

Since Rails 4.0 no more .where('column_name IS NOT NULL'). Instead, we now can use
.where.not(column_name: nil)
Yay!

Sunday, May 19, 2013

RubyMine can't find test_helper

I have been an RSpec user since I started working on Ruby and Rails. I usually run a spec file, which reflect the production code file that I'm currently working on, inside RubyMine. So far it has been working fine out of the box.

As a lot more people start talking about Minitest, I want to give it a try. I was starting a new project today. It was a perfect chance to try out Minitest. I expected it to work perfectly out of the box with RubyMine, but apparently it is not.

I got this error when I tried running my test as usual.
`require': cannot load such file -- test_helper (LoadError)
Basically, it says that Ruby can't find test_helper file that is required in the top of my Minitest test file. I knew that it's LOAD_PATH issue but I didn't actually know how to config it properly since I was spoiled by out of the box RSpec integration.

I did googling around by no luck. There's only a page show how to config Minitest report.

I did try to switch back to RSpec just to see whether it's still working fine, and it is. I looked at the runner command that's generated by RubyMine when we execute the spec. There's nothing special from what it generates for Minitest. It seems like RSpec does some work figuring out the path for us. That's why it works out of the box.

So I aim toward finding a way to manually config properly the test running path. Finally, I figured it out with the clue from this comment.

  • First go to Run > Edit Configurations.
  • On the left panel, select Defaults and Ruby
  • Put the absolute path to your Rails project into Working directory: field
  • Append field Ruby arguments with -Itest (tell Ruby to look into test directory)
  • If you had run the test before, you need to remove all the configurations under Ruby section (outside Defaults) to force them to load the new configuration
  • And enjoy the Minitest experiences! (Should work with TestUnit too)
There's one potential problem with this solution. If you do run any non-test Ruby files, they will always load test directory which you don't want them to. Personally I've never do that so this setup is fine for me.

Thursday, February 21, 2013

Execute one line command on IRB or Rails's console through Unix shell

Basic Unix approach - echo and pipe:
$ echo "<command>" | irb
For example,
$ echo "1 + 1" | irb
1 + 1
2
You can change irb to rails console to execute that command in the Rails environment.

Monday, May 14, 2012

Things I Didn't Know Rails Could Do

Something I thing it's easy and useful to me from James Edward Gray II presentation in RailsConf 2012
Ten Things You Didn't Know Rails Could Do


  • rails c --sandbox
  • rake db:migrate:status
  • pluck
    • User.pluck(:email)
    • User.uniq.pluck(:email)
  • Count Record in Group
    • Model.group(:column).count
  • File.atomic_write
  • { nested: { a: 1 } }.deep_merge(nested: { b: 2 })
  • hash.except(:key1, :key2)
  • hash1.reverse_merge(hash2) # keep hash1 value if hash2 has a duplicate key
  • content_tag_for(:tag, array) { |e| # content_inside }
  • render partial: @active_record_model & to_partial_path
  • grouped_options_for_select

Saturday, March 3, 2012

Personal (and non-popular) Rails development rules of thumb

  • View first, then Controller and Model last.
  • In Controller tests:
    • Don't mock ActiveRecord method
    • Do stub ActiveRecord method (No real SQL execution allowed)
    • Do mock custom model method
    • Use signature from model mock to create real method in model (or module)
    • Should not contain more than 5 lines or 10 function calls
  • In Model tests:
    • Do real SQL execution (No mock, no stub)

Sunday, November 6, 2011

How to add helper method to Cucumber's World

Add this line to any files under features/supports/ directory
World({any_module_names})
Module's name here can be a predefined Rails's helper or your application helper or a new helper which is just created here.

Then you can access method inside the module in all of your Cucumber's step definitions.

Credit: #51 Integration Tests With Cucumber

Saturday, October 29, 2011

[Rails] Redirect to previous page

In controller, you can specify redirection to go back to previous page that call to this controller by using code below:
redirecto_to :back  
Note: Rails 3.1

[Rails] Route alias

You can execute "rake routes" to view display routes in your app.

The first column of output are route aliases which you can refer to in your app or test by append "_path" to that alias.

If you use resource in routes.rb, it will automatically generate CRUD routes and their alias for you.

But if you want to alias your other routes, you can do by append below after your routes
, :as => :{alias you want}
Note: Rails 3.1

Friday, October 28, 2011

[Heroku] Access Rails's model in migration, heroku rake db:migrate, uninitialized constant

I wanted to use Rails's migration to add new column to a table and fill this column with default value.
add_column :students, :student_id, :integer 
Student.all.each { |s| s.update_attributes!(:student_id => s.id+10000) }
I run this locally.
rake db:migrate
It worked without any problem.

Then I deployed to Heroku and run;
heroku rake db:migrate
I found this error.
 uninitialized constant AddStudentIdToStudents::Student
After googling for a while, I found this blog post Heroku Migration Fails to Update Attributes: reset_column_information

The way to solve this issue(don't know why) is to open up the class inside migration file like this;
class AddStudentIdToStudents < ActiveRecord::Migration
  class Student < ActiveRecord::Base; end
  def change
    add_column :students, :student_id, :integer
    Student.all.each { |s| s.update_attributes!(:student_id => s.id+10000) }
  end
end
This works for me.

Note: Rails 3.1.0 

Sunday, October 16, 2011

My Note from "The Intro to Rails Screencast I Wish I Had"

I found that The Intro to Rails Screencast I Wish I Had is very good in demostrating some tricks that make Rails different to other web development frameworks.

Below are notes from my 2nd time watching this screencast. What I note are things that I've never known before or I can't really remember the way to use it.

  • Add -T in rails new to prevent rails from generating Test::Unit
  • Gems
    • turn (Pretty printing for test results)
    • guard-rspec (Autotest)
    • growl_notify
    • rb-fsevent
    • launchy
      • save_and_open_page (use along with Capybara statements)
  • Guard
    • guard init rspec
    • guard (start guard)
  • RSpec integration test
    • rails g integration_test {name}
  • Routes
    • rake routes
    • resources (auto routes)
  • Capybara (route_name comes from first column of rake route)
    • visit {route_name}_path
    • page.should have_content {string}
    • fill_in {id/name/label}, :with => {string}
    • click_button {id/name/label}
    • current_path.should == {route_name}_path
    • find_field('').value
  • ActiveModel
    • {Model}.create {value}
    • {model_instance}.update_attributes {fields hash}
  • ERB
    • form_for {object} do | f |
    • f.label :{name}
    • f.text_field :{name}
    • f.submit
    • render '{partial view(No _)}'  <- partial view file name must prefix with _ 
    • flash.each do | name, message | (come from params passed with redirect_to)
  • Controller
    • render :text => params.inspect
    • redirect_to :back (previous page)
    • (redirect_to) {:notice | :alert} => {string} (will be available in flash)


Saturday, October 8, 2011

Make Rails accept Non-English Characters

Put following line to the first line of the page that contain Non-English characters
# encoding: utf-8

Collectd PostgreSQL Plugin

I couldn't find this link when searching with google https://www.collectd.org/documentation/manpages/collectd.conf.html#plugin-postgresq...