Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

10 Ruby and Rails Pro Tips

1,115 views

Published on

10 Ruby and Rails Pro Tips, for Parisrb meetup.

Published in: Software
  • Be the first to comment

  • Be the first to like this

10 Ruby and Rails Pro Tips

  1. 1. 10 Ruby and Rails Pro Tips Michel Pigassou, Co-founder & CTO at Fidzup, michel@fidzup.com 2014-08-05 A few things you may or may not know
  2. 2. Use debugger Just use it! How? http://guides.rubyonrails.org/debugging_rails_applications.html Bonus: byebug for Ruby 2: https://github.com/deivid-rodriguez/byebug
  3. 3. Inline Assignments Don't: params[:routing_data] ? routing_data = params[:routing_data].to_json : routing_data = {} Do: routing_data = params[:routing_data] ? params[:routing_data].to_json : {}
  4. 4. Fail Fast Integer() and Float() raise an Exception Also Hash#fetch Bonus: Array()
  5. 5. Use Constants and Integers Example: CHOICES = [:female, :male, :unknown].freeze user.sex = CHOICES.index(:female) user.sex = CHOICES[0]
  6. 6. Be Careful with =~ =~ returns an integer or nil ("foo" =~ /foo/) === true #=> false
  7. 7. Eliminate Tautologies Don't: <%= radio_button_tag 'date_field', 'created_at', params[:date_field] == 'created_at' ? true : false %> Do: <%= radio_button_tag 'date_field', 'created_at', params[:date_field] == 'created_at' %>
  8. 8. Use update_column update_attribute runs callbacks update_column doesn't
  9. 9. Avoid nested_attributes Complicated with AJAX and deep nested associations Alternatives: - Do It Yourself - Redtape (https://github.com/ClearFit/redtape)
  10. 10. Useful Gems Annotate (Schema in models) https://github.com/ctran/annotate_models Lograge (Better logs) https://github.com/roidrage/lograge factory_girl (Better fixtures) https://github.com/thoughtbot/factory_girl better_errors https://github.com/charliesome/better_errors
  11. 11. Let the DB Do its Work Filling dates without value: WITH filled_dates as ( select day, 0 as blank_count from generate_series('#{@start_date}', current_date::date, '1 day') as day ), stats as ( SELECT COUNT(*) AS count, date_trunc('day', created_at) AS day FROM "checkins" WHERE (created_at >= '#{@start_date.to_s}') GROUP BY date_trunc('day', created_at) ORDER BY date_trunc('day', created_at) ) SELECT date(filled_dates.day), coalesce(stats.count, filled_dates.blank_count) as count FROM filled_dates LEFT OUTER JOIN stats on stats.day = filled_dates.day ORDER BY filled_dates.day; Also: Postgresql uuid(), MD5(), etc.

×