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

Tuesday, 27 February 2024

an error occurred while installing psych (5.1.2) and bundler cannot continue. windows. Error with psych gem in Ruby on rails

 An error occurred while installing psych (5.1.2), and Bundler cannot continue.

The psych gem does neither install nor run the bundle, In this context I followed the following steps to rectify this error:

1. Update the gems using the following command

gem update

2. bundle install --gemfile

3.  gem update psych --platform=ruby

4. bundle install

5. gem update --system

6. gem pristine openssl --version 3.2.0

7.  Add the below line to the end of your GEMFILE

gem 'psych', '5.1.1'

Then Run the bundle install

bundle i


Monday, 2 March 2015

Important website for ROR - Ruby On Rails

http://guides.rubyonrails.org/

http://railscasts.com/

https://www.codeschool.com/paths/ruby

http://www.toptal.com/ruby-on-rails

fat model, skinny controller in Ruby on Rails

“Fat model skinny controller” is an MVC-based Rails design pattern.

MVC is itself a software design pattern that separates a system into three separate and distinct layers; namely, Model, View, and Controller. MVC strives to ensure a clean separation between each of its layers through clearly defined APIs. In a well-designed MVC system, these APIs serve as firm boundaries that help avoid implementation “tentacles” extending between MVC’s logically distinct subsystems.

The “Fat model skinny controller” design pattern advocates placing as much logic as possible in the Model for (a) maximum reuse and (b) code that is easier to test.

That said, a common pitfall for Rails developers is to end up with “overly bloated” models by adhering too blindly to the “fat model, skinny controller” paradigm. The infamous User model is a prime example of this. Since many Rails apps are about the user entering data into the system, or sharing information with their friends socially, the user model will often gain more and more methods, eventually reaching the point where the user.rb model becomes bulky and unmanageable in size.

A few key alternatives worth considering include:
  • Use of other objects: Extract functionality out of models into other objects (such as Decorators or Service objects)
  • Hexagonal architecture for Rails: Employ a hexagonal architecture that views the application as a hexagon, each side of which represents some sort of external interaction the application needs to have.
  • DCI (Data Context Interaction): Instead of focusing on individual objects, focus on the communication and interactions between data and its context. 

Redirecting to Custom 404 and 500 Pages in Rails

Rails bundles default 404 (file not found), 422 (unprocessable entity), and 500 (internal server error) pages into every newly generated application. While they get the job done, these pages are pretty bland, so in this post I’ll show you how to update them to suit the design of your application. As an example, here’s what the default 404 page looks like:

If you open any Rails application lacking custom error pages, you’ll find this 404 page in the file

public/404.html. Therefore the easiest possible solution to creating custom error pages would be to simply edit each of these files as desired. Once updated, you can view them in your development environment by navigating directly to them (error pages aren’t shown by default in Rails’ development environment when an error occurs; more on this later in the post). For instance to see the custom 404 page you’d navigate to http://0.0.0.0:3000/404.html.

While you could get away with directly modifying the 404.html422.html, and 500.html pages, an alternative approach exists that provides more flexibility in terms of how these errors are handled and eliminates the need to potentially duplicate any layout markup that is otherwise automatically injected into your views. Even better, this alternative approach is accomplished in a few simple steps. Start by modifying your application.rb file, adding the line

config.exceptions_app = self.routes.

 For instance here’s what the MyRailsAppconfig/application.rb file looks like after adding this line:

module MyRailsApp
  class Application < Rails::Application
    config.exceptions_app = self.routes
  end
end

This setting tells Rails to allow any exceptions to be handled by another application, which is in this case the application router.
Next, add the following three lines to the bottom of your config/routes.rb file: 
match '/404', to: 'errors#file_not_found', via: :all
match '/422', to: 'errors#unprocessable', via: :all
match '/500', to: 'errors#internal_server_error', via: :all
The match method is used to match a URL to one or more routes. It’s a bit more flexible than for instance the get method because you can configure it to be triggered in conjunction with anymatching route and HTTP method as opposed to for instance just a route matching the getmethod. You can pass specific HTTP methods into the via option, however we want to match routes in conjunction with any HTTP method, and so I’ve passed all into via.
Save these changes and next generate the errors controller and associated actions referenced in these newly created routes:
$ rails g controller Errors file_not_found unprocessable internal_server_error
Restart your Rails server, and navigate to some random nonexistent page. You’ll see that your development server does not respond as desired. This is because you need to tell Rails to no longer dump detailed debugging information to the HTTP response, a feature that is logically desired during the typical debugging process. You can do this by adding the following line to yourconfig/environments/development.rb file: 
 config.consider_all_requests_local = false
 After having added this line, restart your Rails server again, navigate to a non-existent URL, and you should see the file_not_found default view!

With the dynamic error handlers implemented, you have the convenience of allowing the default layout to be wrapped around the views, and can optionally implement more advanced handlers. For instance you can take advantage of various request methods to retrieve parts of the request (the requested page, parameters, etc) and build in logic that suggests possible desirable destinations!

Filters in Rails

 Filters are essentially callback methods that are run before, after, or “around” a controller action.

  • Before filter methods are run before a controller action and therefore may halt the request cycle. A common before filter is one which requires a user to be logged in for an action to be performed.
  • After filter methods are run after a controller action and therefore cannot stop the action from being performed but do have access to the response data that is about to be sent to the client.
  • Around filter methods are “wrapped around” a controller action. They can therefore control the execution of an action as well as execute code before and/or after the action is performed.

For example, in a website where changes have an approval workflow, an administrator could be able to preview them easily with an around filter as follows:





















Note that an around filter also wraps rendering. In particular, in the example above, if the view reads from the database (e.g., via a scope), it will do so within the transaction and thus present the data to preview. You can also choose not to yield and build the response yourself, in which case the action will not be run.
The order of execution is a bit tricky and is important to understand clearly. Filter methods execute in the following order:
  1. Before filter methods, in order of definition.
  2. Around filter methods, in order of definition.
  3. After filter methods, in reverse order.
Also, because of the way Ruby instantiates classes, the filter methods of a parent class’ before will be run before those of its child classes. 

Processing flow of a Rails Request

At the highest level, Rails requests are served through an application server, which is responsible for directing an incoming request into a Ruby process. Popular application servers that use the Rack web request interface include Phusion Passenger, Mongrel, Thin, and Unicorn.

Rack parses all request parameters (as well as posted data, CGI parameters, and other potentially useful bits of information) and transforms them into a big Hash (Ruby’s record / dictionary type). This is sometimes called the env hash, as it contains data about the environment of the web request.

In addition to this request parsing, Rack is configurable, allowing for certain requests to be directed to specific Rack apps. If you want, for example, to redirect requests for anything in your admin section to another Rails app, you can do so at the Rack level. You can also declare middleware here, in addition to being able to declare it in Rails.

Those requests that are not directed elsewhere (by you in Rack) are directed to your Rails app where it begins interacting with the Rails ActionDispatcher, which examines the route. Rails apps can be spit into separate Rails Engines, and the router sends the request off to the right engine. (You can also redirect requests to other Rack compatible web frameworks here.)

Once in your app, Rails middleware – or your custom middleware – is executed. The router determines what Rails controller / action method should be called to process the request, instantiates the proper controller object, executes all the filters involved, and finally calls the appropriate the action method.

Describe the Rails Asset Pipeline and how it handles assets (such as JavaScript and CSS files)


Rails 3.1 introduced the Asset Pipeline, a way to organize and process front-end assets. It provides an import/require mechanism (to load dependent files) that provides many features. While the Asset Pipeline does have its rough edges, it does solve and provide many of the modern best practices in serving these files under HTTP 1.1. Most significantly, the Asset Pipeline will:
  • Collect, concatenate, and minify all assets of each type into one big file
  • Version files using fingerprinting to bust old versions of the file in browser caches

The Asset Pipeline automatically brings with it Rails’ selection of Coffeescript as its JavaScript pre-processed / transpiled language of choice and SASS as its CSS transpiled language. However, being an extensible framework, it does allow for additional transpiled languages or additional file sources. For example, Rails Assets brings the power of Bower to your Rails apps, allowing you to manage third-party JavaScript and CSS assets very easily.

REST and RESTful Routes in Rails

What is REST?

  •   Representational State Transfer
  •   Don't perform procedures
  •   Perform sate transformations upon resources

Why do we need use REST?
  •  Default routes (using hashes) works
  •  REST is Rails default; optimized for it
  •  Most professional Rails developers use REST
  •  Gives an application an API for free(HTML,XML,JSON etc.,)
  •  Provides conventions,consistent structure, and simplicity
  •  Improves application security

REST Paradigm Requirements

  1.  Organize code into resources - Rails encourages one controller for each model
  2.  Learn HTTP verbs for working with resources - Consider which CRUD  actions are suited for each
  3.  Map a new URL syntax to controller actions - Change Rails routes
  4.  Modify existing links and forms to use new URL syntax - Learn about RESTful route helpers
   














REST in Rails

    <form method="PATCH" action="/subjects/1243">
    #......
    </form>

    <form method="POST" action="/subjects/1243">
    <input type="hidden" name="_method" value="patch"/>
    #......
    </form>

RESTful Routes:

    # config/routes.rb

    resources :subjects do
      member do
        get  :delete
          end
        end














   To know routes in your application: rake routes


RESTful Links and Forms

    RESTful URL Helpers
   
        {:controller => 'subjects', :action => 'show', :id =>5} 
   
         subject_path(5)
  



    <%= link_to ('All Subjects', subjects_path) %>
    <%= link_to ('Show Subject', subject_path(@subject.id)) %>
    <%= link_to ('Edit Subject', edit_subject_path(@subject.id)) %>

    for additional arguments use hash
    <%= link_to ('Edit Subject',
      edit_subject_path(@subject.id, :page => 1, :sort => 'name')) %>

    REST Form Helpers

    form_for(:subject, :url => subject_path(@subject.id),
      :html => {:method => :patch}) do
      #...........
    end

    form_for(@subject) do |f|
     #.....
     end

Using Non-Standard Resources

    resources :admin_users, :except => [:show]
    resources :products,    :only => [:index, :show]

Using Non-Standard Actions

    resources :subjects do
   
      member do
        get :delete     # delete_subject_path(:id)
      end

      collection do
        get :export        # export_subjects_path
      end
    end

Nested Resources

    resources :subjects do
     member do
        get :delete
      end
     
       resources :pages do
         member do
          get :delete
          end
       end

    end




  









  
REST URL Helpers
   
    <%= link_to('All Pages', subject_pages_path(@subject.id)) %>
    <%= link_to('Show Page', subject_page_path(@subject.id, @page.id)) %>
    <%= link_to('Edit Page',
        edit_subject_page_path(@subject.id, @page.id)) %>
    <%= link_to('All Sections',
        subject_page_sections_path(@subject.id, @page.id)) %>
    <%= link_to('Show Section',
        subject_page_section_path(@subject.id, @page.id,@section.id)) %>

Thursday, 18 December 2014

RAILS

Variables are the memory locations which holds any data to be used by any program.

There are five types of variables supported by Ruby. You already have gone through a small description of these variables in previous chapter as well. These five types of variables are explained in this chapter.
Ruby Global Variables:

Global variables begin with $. Uninitialized global variables have the value nil and produce warnings with the -w option.

Assignment to global variables alters global status. It is not recommended to use global variables. They make programs cryptic.

Here is an example showing usage of global variable.

#!/usr/bin/ruby

$global_variable = 10
class Class1
def print_global
puts "Global variable in Class1 is #$global_variable"
end
end
class Class2
def print_global
puts "Global variable in Class2 is #$global_variable"
end
end

class1obj = Class1.new
class1obj.print_global
class2obj = Class2.new
class2obj.print_global

Here $global_variable is a global variable. This will produce following result:

NOTE: In Ruby you CAN access value of any variable or constant by putting a hash (#) character just before that variable or constant.

Global variable in Class1 is 10
Global variable in Class2 is 10

Ruby Instance Variables:

Instance variables begin with @. Uninitialized instance variables have the value nil and produce warnings with the -w option.

Here is an example showing usage of Instance Variables.

#!/usr/bin/ruby

class Customer
def initialize(id, name, addr)
@cust_id=id
@cust_name=name
@cust_addr=addr
end
def display_details()
puts "Customer id #@cust_id"
puts "Customer name #@cust_name"
puts "Customer address #@cust_addr"
end
end

# Create Objects
cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2=Customer.new("2", "Poul", "New Empire road, Khandala")

# Call Methods
cust1.display_details()
cust2.display_details()

Here @cust_id, @cust_name and @cust_addr are instance variables. This will produce following result:

Customer id 1
Customer name John
Customer address Wisdom Apartments, Ludhiya
Customer id 2
Customer name Poul
Customer address New Empire road, Khandala

Ruby Class Variables:

Class variables begin with @@ and must be initialized before they can be used in method definitions.

Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.

Overriding class variables produce warnings with the -w option.

Here is an example showing usage of class variable:

#!/usr/bin/ruby

class Customer
@@no_of_customers=0
def initialize(id, name, addr)
@cust_id=id
@cust_name=name
@cust_addr=addr
end
def display_details()
puts "Customer id #@cust_id"
puts "Customer name #@cust_name"
puts "Customer address #@cust_addr"
end
def total_no_of_customers()
@@no_of_customers += 1
puts "Total number of customers: #@@no_of_customers"
end
end

# Create Objects
cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2=Customer.new("2", "Poul", "New Empire road, Khandala")

# Call Methods
cust1.total_no_of_customers()
cust2.total_no_of_customers()

Here @@no_of_customers is a class variable. This will produce following result:

Total number of customers: 1
Total number of customers: 2

Ruby Local Variables:

Local variables begin with a lowercase letter or _. The scope of a local variable ranges from class, module, def, or do to the corresponding end or from a block's opening brace to its close brace {}.

When an uninitialized local variable is referenced, it is interpreted as a call to a method that has no arguments.

Assignment to uninitialized local variables also serves as variable declaration. The variables start to exist until the end of the current scope is reached. The lifetime of local variables is determined when Ruby parses the program.

In the above example local variables are id, name and addr.
Ruby Constants:

Constants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally.

Constants may not be defined within methods. Referencing an uninitialized constant produces an error. Making an assignment to a constant that is already initialized produces a warning.

#!/usr/bin/ruby

class Example
VAR1 = 100
VAR2 = 200
def show
puts "Value of first Constant is #{VAR1}"
puts "Value of second Constant is #{VAR2}"
end
end

# Create Objects
object=Example.new()
object.show

Here VAR1 and VAR2 are constant. This will produce following result:

Value of first Constant is 100
Value of second Constant is 200

Ruby Pseudo-Variables:

They are special variables that have the appearance of local variables but behave like constants. You can not assign any value to these variables.

*

self: The receiver object of the current method.
*

true: Value representing true.
*

false: Value representing false.
*

nil: Value representing undefined.
*

__FILE__: The name of the current source file.
*

__LINE__: The current line number in the source file.

Ruby Basic Literals:

The rules Ruby uses for literals are simple and intuitive. This section explains all basic Ruby Literals.
Integer Numbers:

Ruby supports integer numbers. An integer number can range from -230 to 230-1 or -262 to 262-1. Integers with-in this range are objects of class Fixnum and integers outside this range are stored in objects of class Bignum.

You write integers using an optional leading sign, an optional base indicator (0 for octal, 0x for hex, or 0b for binary), followed by a string of digits in the appropriate base. Underscore characters are ignored in the digit string.

You can also get the integer value corresponding to an ASCII character or escape sequence by preceding it with a question mark.

Example:

123 # Fixnum decimal
1_234 # Fixnum decimal with underline
-500 # Negative Fixnum
0377 # octal
0xff # hexadecimal
0b1011 # binary
?a # character code for 'a'
?\n # code for a newline (0x0a)
12345678901234567890 # Bignum

NOTE: Class and Objects are explained in a separate chapter of this tutorial.
Floating Numbers:

Ruby supports integer numbers. They are also numbers but with decimals. Floating-point numbers are objects of class Float and can be any of the following:

Example:

123.4 # floating point value
1.0e6 # scientific notation
4E20 # dot not required
4e+20 # sign before exponential

String Literals:

Ruby strings are simply sequences of 8-bit bytes and they are objects of class String. Double-quoted strings allow substitution and backslash notation but single-quoted strings don't allow substitution and allow backslash notation only for \\ and \'

Example:

#!/usr/bin/ruby -w

puts 'escape using "\\"';
puts 'That\'s right';

This will produce following result:

escape using "\"
That's right

You can substitute the value of any Ruby expression into a string using the sequence #{ expr }. Here expr could be any ruby expression.

#!/usr/bin/ruby -w

puts "Multiplication Value : #{24*60*60}";

This will produce following result:

Multiplication Value : 86400

Backslash Notations:

Following is the list of Backslash notations supported by Ruby:
Notation Character represented
\n Newline (0x0a)
\r Carriage return (0x0d)
\f Formfeed (0x0c)
\b Backspace (0x08)
\a Bell (0x07)
\e Escape (0x1b)
\s Space (0x20)
\nnn Octal notation (n being 0-7)
\xnn Hexadecimal notation (n being 0-9, a-f, or A-F)
\cx, \C-x Control-x
\M-x Meta-x (c | 0x80)
\M-\C-x Meta-Control-x
\x Character x

For more detail on Ruby Strings, go through Ruby Strings.
Ruby Arrays:

Literals of Ruby Array are created by placing a comma-separated series of object references between square brackets. A trailing comma is ignored.
Example:

#!/usr/bin/ruby

ary = [ "fred", 10, 3.14, "This is a string", "last element", ]
ary.each do |i|
puts i
end

This will produce following result:

fred
10
3.14
This is a string
last element

For more detail on Ruby Arrays, go through Ruby Arrays.
Ruby Hashes:

A literal Ruby Hash is created by placing a list of key/value pairs between braces, with either a comma or the sequence => between the key and the value. A trailing comma is ignored.
Example:

#!/usr/bin/ruby

hsh = colors = { "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f }
hsh.each do |key, value|
print key, " is ", value, "\n"
end

This will produce following result:

green is 240
blue is 15
red is 3840

For more detail on Ruby Hashes, go through Ruby Hashes.
Ruby Ranges:

A Range represents an interval.a set of values with a start and an end. Ranges may be constructed using the s..e and s...e literals, or with Range.new.

Ranges constructed using .. run from the start to the end inclusively. Those created using ... exclude the end value. When used as an iterator, ranges return each value in the sequence.

A range (1..5) means it includes 1, 2, 3, 4, 5 values and a range (1...5) means it includes 1, 2, 3, 4 values.
Example:

#!/usr/bin/ruby

(10..15).each do |n|
print n, ' '
end

This will produce following result:

10 11 12 13 14 15

For more detail on Ruby Range