rails on davidchua https://dchua.com/tags/rails/ Recent content in rails on davidchua Hugo -- gohugo.io en-us Mon, 16 Jan 2017 00:00:00 +0000 Fixing OmniAuth Redirecting to a URI with Port https://dchua.com/posts/2017-01-16-fixing-omniauth-redirecting-to-a-uri-with-port/ Mon, 16 Jan 2017 00:00:00 +0000 https://dchua.com/posts/2017-01-16-fixing-omniauth-redirecting-to-a-uri-with-port/ Came across this problem the other day when deploying a Rails application that is sitting behind Kubernetes and Deis With my Rails application using OmniAuth and its Facebook strategy, after a user logins, hits Facebook and returns a redirection, the URL returned has its port 80 embedded in the return URI like: https://domain.com:80. In most cases, this wouldn’t be a problem but Facebook would return an error as the return URI (with the port 80) is not whitelisted hence creating a bad flow for your user. Getting Multi-threaded Thin to Work in Development (Rails 4) https://dchua.com/posts/2015-12-03-getting-thin-to-work-in-development/ Thu, 03 Dec 2015 00:00:00 +0000 https://dchua.com/posts/2015-12-03-getting-thin-to-work-in-development/ Rails 4 If you’re attempting to run thin to work in threaded mode for the very first time, you might encounter that no matter what you do, your site won’t load. Running $ thin start --threaded Will return the typical startup output >> Thin web server (v1.5.1 codename Straight Razor) >> Maximum connections set to 1024 >> Listening on 0.0.0.0:3005, CTRL+C to stop But you’ll never be able to access the site no matter what you do. How to Test for File Operations with FakeFS and RSpec https://dchua.com/posts/2014-12-24-how-to-test-for-file-operations-with-fakefs-and-rspec/ Wed, 24 Dec 2014 00:00:00 +0000 https://dchua.com/posts/2014-12-24-how-to-test-for-file-operations-with-fakefs-and-rspec/ Background: Say you have controller method that creates and writes into a file and you’d like to be able to run expectations on the behavior and not so much of the implementation. The normal way would be to do something like: def test_creates_directory FileUtils.expects(:mkdir).with("directory").once Library.add "directory" end because this just doesn’t work. def test_creates_directory Library.add "directory" assert File.directory?("directory") end So one way to solve this is with this gem called FakeFS. Fix AngularJS from loading twice error on Rails 4 https://dchua.com/posts/2014-11-16-fix-angularjs-from-loading-twice-error-on-rails-4/ Sun, 16 Nov 2014 00:00:00 +0000 https://dchua.com/posts/2014-11-16-fix-angularjs-from-loading-twice-error-on-rails-4/ If you’re running a Rails 4.x app with AngularJS, and you’re getting increasingly frustrated with receiving “AngularJS loaded twice” errors and you can’t seem to figure out what went wrong, perhaps you might want to make sure you do two things first: First, remove Turbolinks Gem Remove require ‘turbolinks’ from your application.js It is not apparent at first but turbolinks inject its own form of javascript into your views and when run, it will actually overwrite your normal angular behavior. How to fix BigDecimal returning as Strings in Rails https://dchua.com/posts/2014-11-06-activesupport-encodes-bigdecimals-as-strings/ Thu, 06 Nov 2014 00:00:00 +0000 https://dchua.com/posts/2014-11-06-activesupport-encodes-bigdecimals-as-strings/ Something that I’ve just found out recently. Basically, Rails serializes BigDecimal objects as JSON strings because they didn’t want its values to be misintepreted when deserialized. But in Rails 4.0.x, an option to reverse that behavior was introduced in the form of: # config/application.rb ActiveSupport.encode_big_decimal_as_string = false # default = true If you’re on Rails 4.0.x, adding the above will ensure that the values returned will be numbers. If your Rails API is providing response data that contains numbers, you want to make sure that you are not accidentally encoding big decimals as string, which would cause a problem when trying to do arithmetic calculations with it. How to Generate PDFs with HTML templates in 10 minutes with Rails https://dchua.com/posts/2014-10-30-generate-pdfs-with-html-templates-in-rails/ Thu, 30 Oct 2014 00:00:00 +0000 https://dchua.com/posts/2014-10-30-generate-pdfs-with-html-templates-in-rails/ Generating PDF for your webapplication is not that difficult as you think. There are many ways to do this, and there’s another great gem out there that does this functionality quite well too, called Prawn, but for the purpose of todays' tutorial, I’ll be going through another popular gem called wicked_pdf instead. WickedPDF uses wkhtmltopdf which allows you to generate PDFs directly from HTML without having to adhere to a DSL. Configure legacy timestamp attributes in Activerecord https://dchua.com/posts/2014-08-19-configure-legacy-timestamp-attributes-in-activerecord/ Tue, 19 Aug 2014 00:00:00 +0000 https://dchua.com/posts/2014-08-19-configure-legacy-timestamp-attributes-in-activerecord/ In ActiveRecord, when working with legacy database and the existing database uses different fields for last_update and created_at, how do you specify the correct column names for ActiveRecord to properly record timestamps? # in your config/initializers directory, create a new file # `active_record_patch.rb` # overload module ActiveRecord module Timestamp private def timestamp_attributes_for_create #:nodoc: [:created_at, :created_on, :create_date, :post_date] end def timestamp_attributes_for_update #:nodoc: [:modtime, :updated_on, :modified_at, :updated_at, :last_update] end end end DRY your ActionMailer::Base.deliveries.clear in RSpec tests https://dchua.com/posts/2014-08-12-dry-your-actionmailer-base.deliveries.clear-in-rspec-tests/ Tue, 12 Aug 2014 12:22:03 +0800 https://dchua.com/posts/2014-08-12-dry-your-actionmailer-base.deliveries.clear-in-rspec-tests/ When testing for mailers, you might need to add the following quite frequently: describe "test mailer" do it "should work" do ActionMailer::Base.deliveries.clear # bunch of other # codes here end end You probably would add them at the start of every test block that tests for ActionMailer. The neater way would be to do this: describe "test mailer", type: :mailer do it "should work" do # bunch of # codes here end end By assigning a mailer_type to the test describe, RSpec will automatically clear the actionmailer deliveries at the start. Creating my first Rack Middleware with Rack::ContentLength https://dchua.com/posts/2014-06-19-creating-my-first-rack-middleware/ Thu, 19 Jun 2014 00:00:00 +0000 https://dchua.com/posts/2014-06-19-creating-my-first-rack-middleware/ Yeah, I’m probably pretty slow in the game but I think I’ve finally wrapped my head around all the countless Rack Middlewares out there. The goal of this was to create a response_logger that intercepts the response object on the middleware level and send out a log with the size of the JSON object that it returns for future reference. I first setup Rack::ContentLength, which is a great Middleware that’s available out of the box if you’re on Rails. The Mystery Behind Ruby Require and Load Paths https://dchua.com/posts/2013-09-12-the-mystery-behind-ruby-require-and-load-paths/ Thu, 12 Sep 2013 00:00:00 +0000 https://dchua.com/posts/2013-09-12-the-mystery-behind-ruby-require-and-load-paths/ Ruby require used to annoy the hell out of me. Because back then I didn’t know how to use it, or what exactly it does. I knew that I need to ‘require’ in order to use custom Classes I’ve created. But what to put in the ‘require …’, has always been trial and error for me. Basically, ‘require’ takes in a param which contains the path to your custom class(es) that is stored in a . Tail Rails Production Logs from Capistrano https://dchua.com/posts/2013-08-21-tail-rails-production-logs-from-capistrano/ Wed, 21 Aug 2013 00:00:00 +0000 https://dchua.com/posts/2013-08-21-tail-rails-production-logs-from-capistrano/ Found this nifty snippet today which would allow you to tail your production logs without leaving your local terminal. # capistrano desc "tail production log files" task :tail_logs, :roles => :app do trap("INT") { puts 'Interupted'; exit 0; } run "tail -f #{shared_path}/log/production.log" do |channel, stream, data| puts # for an extra line break before the host name puts "#{channel[:host]}: #{data}" break if stream == :err end end I put mine in the ‘rails’ namespace, so all I have to do is a nice: Capistrano - Setup log directories and database.yml https://dchua.com/posts/2013-08-17-capistrano-setup-log-directories-and-database-yml/ Sat, 17 Aug 2013 00:00:00 +0000 https://dchua.com/posts/2013-08-17-capistrano-setup-log-directories-and-database-yml/ Updated my deploy.rb gist. Created a new setup_config task that should be run the first time you setup your server. This fixes the missing database.yml file, and setups the missing log directories in your Rails app. Also creates a helper method that checks if a remote_file exists. # config/deploy.rb before 'deploy:db:symlink_db', 'deploy:setup_config' def remote_file_exists?(full_path) 'true' == capture("if [ -e #{full_path} ]; then echo 'true'; fi").strip end namespace :deploy do task :setup_config do run " Rspec Generator Files https://dchua.com/posts/2013-08-10-rspec-generator-files/ Sat, 10 Aug 2013 00:00:00 +0000 https://dchua.com/posts/2013-08-10-rspec-generator-files/ If RSpec for some reason doesn’t generate your spec files when generating models and controllers, add this to your config/application.rb. config.generators do |g| g.test_framework :rspec, :fixtures = true, :view_specs = false, :helper_specs = false, :routing_specs = false, :controller_specs = true, :request_specs = true g.fixture_replacement :factory_girl, :dir = "spec/factories" end SimpleCov for Spork/RSpec (Code Test Coverage) https://dchua.com/posts/2013-08-06-simplecov-for-sporkrspec-code-test-coverage/ Tue, 06 Aug 2013 00:00:00 +0000 https://dchua.com/posts/2013-08-06-simplecov-for-sporkrspec-code-test-coverage/ If you’re into testing, you know about test coverages. Some developers aim to strive 100% coverage, but personally, I’d avoid being dogmatic about test coverage. After all test coverage is doesn’t ensure that your code is well tested. But if you’re into test coverage, or just want a quick and easy way to view your team’s test progress, this gem, simplecov, maybe what you’re looking for. SimpleCov generates a HTML report in coverage/ located in your Rails. Resque your RSpec https://dchua.com/posts/2013-07-31-resque-your-rspec/ Wed, 31 Jul 2013 00:00:00 +0000 https://dchua.com/posts/2013-07-31-resque-your-rspec/ To start testing your Resque: Use the awesome ResqueSpec # Gemfile group :test do ... gem 'resque_spec' ... end In your spec testing, play around with “have_queue_size_of” and “have_queued”. Example, if you have a worker called SoldPropertyMessenger with its perform action taking in a param of an ‘id’ # app/workers/sold_property_messenger.rb class SoldPropertyMessenger @queue = :notification def self.perform(id) # magic end end Your spec/controller test could do something like: Howto: Multiple Redis Database for Different Rails Environment https://dchua.com/posts/2013-07-30-howto-multiple-redis-database-for-environment/ Tue, 30 Jul 2013 00:00:00 +0000 https://dchua.com/posts/2013-07-30-howto-multiple-redis-database-for-environment/ This is a personal note to self. Referenced from a post on Stackoverflow. One problem I had with running Redis on my Rails app was that on the default configuration, Redis can’t tell if you’re on development or production and hence when doing tests, you may overwrite your development data. To solve this, lets setup redis to use the correct database for the correct environment: Add config/redis.yml #config/redis.yml default: host: localhost port: 6379 development: db: 0 # namespace: appname_dev test: db: 1 # namespace: appname_test production: db: 2 host: localhost # namespace: appname_prod Update the config/initializer/redis. Redis::InheritedError during RSpec/Spork Testing https://dchua.com/posts/2013-07-30-redisinheritederror-during-rspecspork-testing/ Tue, 30 Jul 2013 00:00:00 +0000 https://dchua.com/posts/2013-07-30-redisinheritederror-during-rspecspork-testing/ When testing an action that performs a redis-rb command on RSpec, you may run into an error: Redis::InheritedError (Tried to use a connection from a child process without reconnecting ... Solve it by adding the following into your spec_helper. # spec/spec_helper.rb RSpec.configure do |config| # ... config.before :all do $redis.client.reconnect end # ... end Saves me ton of time. Reference: Stackoverflow Loading 'deploy/assets' in Capistrano, automatically precompiles:assets https://dchua.com/posts/2013-07-14-loading-deployassets-in-capistrano-automatically-precompilesassets/ Sun, 14 Jul 2013 00:00:00 +0000 https://dchua.com/posts/2013-07-14-loading-deployassets-in-capistrano-automatically-precompilesassets/ Something that I’ve just figured out after tinkering for a couple of hours. Hope this will save someone else some trouble. So I’m running my own custom Capistrano script that on fresh deploy setup a symlink of database.yml on the app instance, so that you don’t need to check in your database.yml file. So in my config/deploy.rb, I have something like: after 'deploy:update_code', 'deploy:symlink_db', 'deploy:assets:precompile' . . . . desc " Testing PaypalExpress Gateway on ActiveMerchant https://dchua.com/posts/2013-06-24-testing-paypalexpress-gateway-on-activemerchant/ Mon, 24 Jun 2013 00:00:00 +0000 https://dchua.com/posts/2013-06-24-testing-paypalexpress-gateway-on-activemerchant/ Background: ActiveMerchant’s BogusGateway class which is usually used in a Test environment, does not have setup_purchase/setup_authorization method which is used in Paypal’s Express Checkout. This gives an: undefined method `setup_purchase' for # When testing for controller actions that interact with ActiveMerchant’s Paypal Express Gateway. To fix this, according to Skud, you will need to download and unpack the active_merchant and active_utils gems into your local vendor directory. /webapps/myapp/$ gem unpack /path/to/activemerchant-1. Custom Exception Handling https://dchua.com/posts/2013-03-10-custom-exception-handling/ Sun, 10 Mar 2013 00:00:00 +0000 https://dchua.com/posts/2013-03-10-custom-exception-handling/ Note to self: For some better practice, handle custom exceptions by: Declaring a custom exception module. # In /lib/exceptions/app_exception.rb module AppException class AnyExceptionName < StandardError end end Do try and keep to the relevant exception subclasses (ie. StandardError v Error). Refer to this. # In /config/application.rb # ensure that autoload path is un-commented to allow rails to load your custom exception library config.autoload_paths += %W(#{config.root}/lib/exceptions) Now, you can raise AppException::AnyExceptionName anytime you want! Speed up assets:precompile in Capistrano https://dchua.com/posts/2013-03-02-assets-precompile-passenger/ Sat, 02 Mar 2013 00:00:00 +0000 https://dchua.com/posts/2013-03-02-assets-precompile-passenger/ Note to self. In order to speed up assets:precompile on passenger production, add the following to config/deploy.rb: namespace :deploy do namespace :assets do task :precompile, :roles => :web, :except => { :no_release => true } do from = source.next_revision(current_revision) if capture("cd #{latest_release}&& #{source.local.log(from)}vendor/assets/ app/assets/ | wc -l").to_i > 0 run %Q{cd #{latest_release}&& #{rake}RAILS_ENV=#{rails_env}#{asset_env}assets:precompile} else logger.info "Skipping asset pre-compilation because there were no asset changes" end end end end Alt: set :max_asset_age, 2 ## Set asset age in minutes to test modified date against. Pusher + Slanger - Publish away! https://dchua.com/posts/2013-01-29-pusher-slanger-publish-away/ Tue, 29 Jan 2013 00:00:00 +0000 https://dchua.com/posts/2013-01-29-pusher-slanger-publish-away/ Played around with Pusher today. Surprisingly, it was an easy push. If you haven’t heard about Pusher, it is a hosted API that allows you to quickly build publish-subscribe messaging functionality into your web application. Like most hosted APIs, they work on a freemium model and charge only when you use up to 100 concurrent connections at a time. Pusher provides a pusher-gem which lets your Rails controllers send out publish messages. Bypassing mass-assignment protection in rake db:seed https://dchua.com/posts/2012-12-19-bypassing-mass-assignment-protection-in-rake-dbseed/ Wed, 19 Dec 2012 00:00:00 +0000 https://dchua.com/posts/2012-12-19-bypassing-mass-assignment-protection-in-rake-dbseed/ Reference: GilesBowkett So I ran this problem the other day on a project where the db/seed.rb file couldn’t run due to mass-assignment protection. Instead of adding the attribute in attr_accessible on the model side and then removing it after running the seed data, there’s actually another way to do it. Giles suggested adding attr_accessible directly into the seed file itself, such that it will temporarily disable mass-assignment protection for the duration of the rake db:seed. Some tips to deploying Rubber-powered EC2 Rails Apps https://dchua.com/posts/2012-01-07-some-tips-to-deploying-rubber-powered-ec2-rails-apps/ Sat, 07 Jan 2012 00:00:00 +0000 https://dchua.com/posts/2012-01-07-some-tips-to-deploying-rubber-powered-ec2-rails-apps/ I’ve been playing around with Rubber, the EC2 deployment script for Rails lately and I’ve spent a huge amount of time trying to get it to work. Here are some of my notes: To setup: # Put this into Gemfile gem rubber Vulcanize! (Create the deployment scripts according to your specifications) On Rails 3.x, in your Rails application’s root directory davidc@davidc:~/my/awesome/app> vulcanize <option> # with option being any one of the following minimal_nodb, redis, passenger_nginx, complete_passenger_nginx, cruise, postgresql, resque, apache, sphinx, monit, minimal_passenger_nginx, mysql_cluster, complete_passenger_postgresql, cassandra, mongodb, complete_mongrel_mysql, complete_passenger_nginx_postgresql, base, memcached, minimal_mysql, complete_passenger_mysql, complete_passenger_nginx_mysql, munin, mysql_proxy, complete_passenger, mysql, nginx, jetty, passenger, haproxy, mongrel Edit /config/rubber/rubber. Rails 3.2 RC1 released! https://dchua.com/posts/2011-12-20-rails-3-2-rc1-released/ Tue, 20 Dec 2011 00:00:00 +0000 https://dchua.com/posts/2011-12-20-rails-3-2-rc1-released/ Woke up this morning to a tweet by DHH: Rails 3.2 (Release Candidate 1) has been released! And it has pretty exciting features to boot like: Faster dev mode & routing Explain queries Tagged logger ActiveRecord Store I’m in particularly excited about tagged logging. For far too long, developers have to struggle with trying to figure out whose Logger.info belonged to who. Can’t wait to try them out. Rails 3.1x Migration Change https://dchua.com/posts/2011-12-13-rails-3-1x-migration-change/ Tue, 13 Dec 2011 00:00:00 +0000 https://dchua.com/posts/2011-12-13-rails-3-1x-migration-change/ If you’re on Rails 3.1, you’ll probably notice that the methods in your migration files have changed from ‘up’ and its corresponding ‘down’ to just a simple ‘change’. So don’t be the surprised the next time you handle migrations. Rails 3.1 makes migrations smarter by providing a new change method. This method is preferred for writing constructive migrations (adding columns or tables). The migration knows how to migrate your database and reverse it when the migration is rolled back without the need to write a separate down method. Omniauth - Easy Authentication for your Rails Projects https://dchua.com/posts/2011-02-18-omniauth-easy-authentication-for-your-rails-projects/ Fri, 18 Feb 2011 00:00:00 +0000 https://dchua.com/posts/2011-02-18-omniauth-easy-authentication-for-your-rails-projects/ I just came across this wonderful little gem that makes authentication on your rails application a breeze. This is exactly the gem that I wished was around a year ago when I was developing Baboonza.com (now defunct) and my various mini project sites. Usually when I start a new rails project, I would use Authlogic and tweaked it to allow openid authentication. If you’ve used authlogic before, you would know that the entire process of just installing the gem and getting all your user models and controllers setup is god awful tedious. Create authlogic apps on Rails 3.x easily https://dchua.com/posts/2011-02-07-create-authlogic-apps-on-rails-3-x-easily/ Mon, 07 Feb 2011 00:00:00 +0000 https://dchua.com/posts/2011-02-07-create-authlogic-apps-on-rails-3-x-easily/ Sometime ago, I’ve created a authlogic rails application template to help me create from scratch a rails 3.x app with authentication. This template would generate the necessary models and migration files to get you running in just a few steps. I’ve created this because of an itch. I hate the process of creating a rails application, installing the authlogic gem, editing the various files. While its relatively simple, it gets annoying when you have to do the same steps many times manually. How to consume Project Nimbus dataservices in Ruby https://dchua.com/posts/2010-10-13-how-to-consume-project-nimbus-dataservices-in-ruby/ Wed, 13 Oct 2010 00:00:00 +0000 https://dchua.com/posts/2010-10-13-how-to-consume-project-nimbus-dataservices-in-ruby/ Project Nimbus is a community initiative by developers working in key corporations and government agencies in Singapore that aims to open up data and services for local innovators who wants to create applications with localized data. The project is current supported by a mix of government agencies like LTA, NEA as well as private businesses/startups like Chlkboard and Shownearby. The list is no where exhaustive and the dataset curators are constantly updating their site with new data providers, so please refer to the Project Nimbus page for a more up to date list. Viewing custom/default error pages on development mode https://dchua.com/posts/2010-03-10-viewing-customdefault-error-pages-on-development-mode/ Wed, 10 Mar 2010 00:00:00 +0000 https://dchua.com/posts/2010-03-10-viewing-customdefault-error-pages-on-development-mode/ Working in development environment, we tend to miss out seeing production-level 404, 500 etc. error codes.By changing the following line to false in your config/environments/development.rb config.action_controller.consider_all_requests_local = true We get to display your custom/default error pages instead of an all so information stack trace. Perfectline Blog explains By default, Rails displays the error pages only in production mode. In development mode you get the all-so-informational exception descriptions and stacktraces. This behavior boils down to Rails either considering your request local (and displaying the full debug message) or “remote” (which means the application is probably in production and/or the debug messages should not be displayed). Holding current rails location for future redirection https://dchua.com/posts/2009-11-15-holding-current-rails-location-for-future-redirection/ Sun, 15 Nov 2009 00:00:00 +0000 https://dchua.com/posts/2009-11-15-holding-current-rails-location-for-future-redirection/ I always have this problem of redirects not going back to the exact page that I want it to. After chatting with some of the rails developers at #rubyonrails on freenode, they’ve provided me with this handy code snipplet to save the current page location temporary and after redirecting it, destroy that temporary location. We can return to this location by calling #redirect_back_or_default. def hold_location session[:return_to] = request.request_uri end # Redirect to the URI stored by the most recent hold_location call or # to the passed default.