Practical Web Programming
Showing posts with label rails. Show all posts
Showing posts with label rails. Show all posts

Sunday, July 10, 2016

How to Debug Rails Application Using Pry Remote

1. Add pry remote in gemfile

gem 'pry-remote', '~> 0.1.8' 
gem 'pry-nav', '~> 0.2.4' 


2. Run bundle install in the terminal 


3. Add the following line in application.rb:

require 'pry-remote'
 
 
4. Add the following in the code where you want to stop executing and debug:

binding.remote_pry


 5. Load the application in the browser. The application will stop execution once it encounters the binding.remote_pry line


6. Open up a new terminal and run the following code:

pry-remote


7. To navigate in the terminal, use the following command:

step
next
continue
exit
 

Saturday, January 09, 2016

Deploying Rails Application for the First Time

I always forget these steps when deploying a Rails app for the first time. So I'm finally writing this in as a guide for the future.

This assumes that you already have a running Ubuntu server with Apache and Passenger installed (see Basic Security Installs for Ubuntu and How to Install Passenger + Apache in Ubuntu).
  1. Clone the git repo.
    git clone git@bitbucket.org:kabalweg/app_name.git
    cd app_name
    bundle install
    
    If you get a "bundle not yet installed" error, run the following comment:
    gem install bundle
    
  2. Go to /var/www/ type and this command to create a symbolic link.
    sudo ln -s /home/kabalweg/app_name/ ./app_name
    
  3. Go to /etc/apache2/sites-available and create a virtualhost file, app_name.conf, or copy and existing one and edit the appropriate values in that file and save.
    <VirtualHost *:80>
        ServerName app_name.net
        Redirect permanent / http://www.app_name.net/
    </VirtualHost>
    
    <VirtualHost *:80>
      ServerName www.app_name.net
      ServerAdmin kabalweg@gmail.com
    
      # Set the environment to production
      RailsEnv production
    
      <IfModule mod_passenger.c>
          # Set to on when debugging errors
          PassengerFriendlyErrorPages off
    
          #PassengerRoot /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini
          #PassengerDefaultRuby /home/kabalweg/.rvm/gems/ruby-2.2.1@rails4.2/wrappers/ruby
          PassengerMaxPoolSize 2
          PassengerPoolIdleTime 0
          PassengerMaxRequests 1000
        </IfModule>
    
        DocumentRoot /var/www/app_name/public
        <Directory /var/www/app_name/public>
          AllowOverride all
          Options -MultiViews
          #Require all granted
          Order deny,allow
          Allow from all
        </Directory>
    
        ErrorLog ${APACHE_LOG_DIR}/error.log
    
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>
    
  4. Disable the default virtualhost and enable the new virtualhost file and activate it.
    sudo a2dissite 000-default.conf
    
    sudo a2ensite app_name.conf
    sudo apachectl -k graceful
    
  5. Generate secret key and put the resulting key in the secret.yml file.
    rake secret RAILS_ENV=production
    
    Note: It's not a good and safe practice to put production config values in the repo. A good way is to ignore config files (*.yml) using git so it don't get save in the repo, then just manually create this files, with the correct values, in the production server.
  6. Pre-compile assets.
    rake assets:precompile RAILS_ENV=production
    
  7. Restart application by typing below in your application's root directory.
    touch tmp/restart.txt
    
    Create this folder (tmp) if you don't have this.

How to Install Passenger + Apache in Ubuntu 16.04 LTS

Note: This assumes that you already have a running Ubuntu server. To install basic security in Ubuntu, see Basic Security Installs for Ubuntu. This instructions was extracted from here.
  1. Install Apache Server
      sudo apt-get update
      sudo apt-get install apache2
      
  2. Set Global ServerName to Suppress Syntax Warnings: "AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message"
      sudo vim /etc/apache2/apache2.conf
      
    and enter at the end of the file:
      ServerName server_domain_or_IP
      
  3. Test config so far
      sudo apache2ctl configtest
      
  4. Restart Apache for the changes to take effect
      sudo systemctl restart apache2
      
  5. Install Passenger packages.
    # Install our PGP key and add HTTPS support for APT
    sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 561F9B9CAC40B2F7
    sudo apt-get install -y apt-transport-https ca-certificates
    
    # Add our APT repository
    sudo sh -c 'echo deb https://oss-binaries.phusionpassenger.com/apt/passenger xenial main > /etc/apt/sources.list.d/passenger.list'
    sudo apt-get update
    
    # Install Passenger + Apache module
    sudo apt-get install -y libapache2-mod-passenger
    
    These commands will install Passenger + Apache module through Phusion's APT repository.
  6. Enable the Passenger Apache module and restart Apache
    sudo a2enmod passenger
    sudo apache2ctl restart
    
  7. Check installation
    sudo passenger-config validate-install
    
    All checks should pass. If any of the checks do not pass, please follow the suggestions on screen.
  8. Check whether Apache has started the Passenger core processes by running the following:
    sudo passenger-memory-stats
    

Friday, January 08, 2016

Creating a Skeleton Rails Application without Database and Test Unit

  1. 1. Create application without database access and test unit
        $ rails new [app_name] --skip-active-record --skip-test-unit
    
  2. Include Bootstrap
    • Download Bootstrap and extract content
    • Copy bootstrap.min.css and bootstrap.css to /app/assets/css folder
    • Copy bootstrap.min.js and bootstrap.js to /app/assets/js folder
    • Copy fonts folder to /app/assets folder
    Note: The reason why I put bootstrap.css in the main root of asset folder is so I can create a file (ex: custom.css) that will over ride the Bootstrap.css rules in case I want to.
  3. Create main controller that will serve as root file.
  4.     $ rails generate controller main_controller index --no-assets --no-helper
    
  5. Set the root route to main_controller#index
        root 'main_controller#index'
    

Wednesday, June 18, 2014

Better Way to Generate Rails Application

Generate project with RMV.

$ mkdir myapp                                                           # create the project folder
$ cd myapp
$ rvm use ruby-2.1.1@myapp --ruby-version --create     # create a new project-specific gemset
                                                                                 # option “—ruby-version” creates .ruby-version and .ruby-gemset files in the root directory
$ gem install rails --pre                                                # installs the most recent release of Rails 
$ rails new .                                                               # generate application in the current directory.


If you have no RVM in your system, follow command below.  

$ \curl -L https://get.rvm.io | bash -s stable --ruby        # install rvm and ruby

$ rvm get stable --autolibs=enable                              # if you have rvm already, update it
$ rvm install ruby                                                      # install Ruby

$ rvm --default use ruby-2.1.1                                    # use and set it as default

$ gem update --system                                             # update gem


Wednesday, October 23, 2013

Automatically Run Tests with Guard

Step by step guide:

1) Edit the Gemfile:
    group :development, :test do
      gem 'guard-rspec', '1.2.1'
    end
    
    # Add System-dependent gems
    group :test do
      gem 'capybara', '1.1.2'
      
      # Test gems on Macintosh OS X
      gem 'rb-fsevent', '0.9.1', :require => false
      gem 'growl', '1.0.3'
      
      # Test gems on Linux
      gem 'rb-inotify', '0.8.8'
      gem 'libnotify', '0.5.9'
      
      # Test gems on Windows
      gem 'rb-fchange', '0.0.5'
      gem 'rb-notifu', '0.0.4'
      gem 'win32console', '1.3.0'
    end 

2) Run the bundler.
    $ bundle install

3) Initialize Guard so that it works with RSpec.
    $ bundle exec guard init rspec

4) Edit the resulting Guardfile so that Guard will run the right tests when the integration tests and views are updated
    require 'active_support/core_ext'

    guard 'rspec', :version => 2, :all_after_pass => false do  # Ensures that Guard doesn’t run all the tests after a failing test (to speed up the Red-Green-Refactor cycle).
      .
      .
      .
      watch(%r{^app/controllers/(.+)_(controller)\.rb$})  do |m|
        ["spec/routing/#{m[1]}_routing_spec.rb",
         "spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb",
         "spec/acceptance/#{m[1]}_spec.rb",
         (m[1][/_pages/] ? "spec/requests/#{m[1]}_spec.rb" : 
                           "spec/requests/#{m[1].singularize}_pages_spec.rb")]
      end
      watch(%r{^app/views/(.+)/}) do |m|
        (m[1][/_pages/] ? "spec/requests/#{m[1]}_spec.rb" : 
                           "spec/requests/#{m[1].singularize}_pages_spec.rb")
      end
      .
      .
      .
    end

5) Start guard
    $ bundle exec guard

NOTE:
To clear the screen everytime guard runs, add -c parameter. Ex: guard -c
If you get a Guard error complaining about the absence of a spec/routing directory, you can fix it by creating an empty one: $ mkdir spec/routing

Use Factory_Girl to Create Mock Data

Step by step guide"

1) Edit the Gemfile
    group :test do
        .
        .
        .
        gem 'factory_girl_rails', '4.1.0'
    end

2) Install it
    $ bundle install

3) Factory Girl format for Person model
    FactoryGirl.define do
      factory :person do
        name     "Michael Hartl"
        email    "michael@example.com"
        password "foobar"
        password_confirmation "foobar"
      end
    end

Generate Rails Application with RSpec

Step by step guide:

 1) Generate a new application without the default Test:Unit
$ rails new sample_app --skip-test-unit

2) Add the RSpec gem in the Gemfile
 group :development, :test do
   gem 'rspec-rails', '2.11.0'
      gem 'shoulda-matchers'
 end
 
 # Add PostgreSQL for production (optional).
 group :production do
   gem 'pg', '0.12.2'
 end

3) Include the Capybara gem, which allows us to simulate a user's interaction with the sample application using a natural English-like syntax.
 group :test do
   gem 'capybara', '1.1.2'
 end

4) Install the gems with "--without production" option. This is a remembered option, which means that we don't have to include it in future invocations of Bundler. Instead, we can write simply bundle install and production gems will be ignored automatically.
 $ bundle install --without production

5) Configure Rails to use RSpec (Note the single colon ":").
 $ rails generate rspec:install  
Note: Add --format doc in .rspec file to make the test output hierarchical

 6) Generate a model with
 $ rails generate model Person  # This will create the model class, migration and test

7) Fill-up the migration and run it 9) Run the test. If the following error "Cannot find table 'people'", it's because the test database is not ready.
    $ rake db:test:prepare              # This just ensures that the data model from the development database (db/development.sqlite3) is reflected in the test database (db/test.sqlite3)

Recent Post