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

Saturday, June 7, 2014

Notes - Rails Tutorial - Chapter 6

let http://www.railstutorial.org/book/modeling_users#sidebar-let
From Michael Harl's Rails Tutorial Chapter 6 Box 6.3. Using let
RSpec’s let method provides a convenient way to create local variables inside tests. The syntax might look a little strange, but its effect is similar to variable assignment. The argument of let is a symbol, and it takes a block whose return value is assigned to a local variable with the symbol’s name. In other words, 
let(:found_user) { User.find_by(email: @user.email) } 
creates a found_user variable whose value is equal to the result of find_by. We can then use this variable in any of the before or it blocks throughout the rest of the test. One advantage of let is that it memoizes its value, which means that it remembers the value from one invocation to the next. (Note that memoize is a technical term; in particular, it’s not a misspelling of “memorize”.) In the present case, because let memoizes the found_user variable, the find_by method will only be called once whenever the User model specs are run.
specify method -
This is just a synonym for it, and can be used when writing it would sound unnatural.

reload method for reloading a value from the database and the eq method for testing equality.
debug method
controller: static_pages
action: home 
This is a YAML3 representation of params, which is basically a hash, and in this case identifies the controller and action for the page.
params variable

Rails comes equipped with three environments: test, development, and production. The default environment for the Rails console is development:

Thursday, May 29, 2014

Notes - Rails Tutorial Chapter 7

== === eq? equal? 
http://stackoverflow.com/questions/7156955/whats-the-difference-between-equal-eql-and

Db:rest
Josh found:

http://stackoverflow.com/questions/10301794/difference-between-rake-dbmigrate-dbreset-and-dbschemaloadhttp://rake.rubyforge.org/

Rails comes equipped with three environments: test, development, and production. The default environment for the Rails console is development:

If you ever need to run a console in a different environment (to debug a test, for example), you can pass the environment as a parameter to the console script:

  $ rails console test

As with the console, development is the default environment for the local Rails server, but you can also run it in a different environment:

  $ rails server --environment production
If you view your app running in production, it won’t work without a production database, which we can create by running rake db:migrate in production:

  $ bundle exec rake db:migrate RAILS_ENV=production

REST!!!!!
POST, GET, PATCH, and DELETE
When following REST principles, resources are typically referenced using the resource name and a unique identifier.

show when Rails’ REST features are activated, GET requests are automatically handled by the show action.
HTTP requestURLActionNamed routePurpose
GET/usersindexusers_pathpage to list all users
GET/users/1showuser_path(user)page to show user
GET/users/newnewnew_user_pathpage to make a new user (signup)
POST/userscreateusers_pathcreate a new user
GET/users/1/editeditedit_user_path(user)page to edit user with id1
PATCH/users/1updateuser_path(user)update user
DELETE/users/1destroyuser_path(user)delete user
______________________________________________________________________________________________________________________________________________________________________

Here we’ve used params to retrieve the user id. When we make the appropriate request to the Users controller, params[:id] will be the user id 1, so the effect is the same as the find method
@user = User.find(params[:id])
User.find(1)
Technically, params[:id] is the string "1", but find is smart enough to convert this to an integer.

Factory Girl is a DSL for defining Active Record objects.

Monday, May 26, 2014

Notes - Rails Tutorial Chapter 4

This is a great "Intro to Ruby" chapter. It is really helpful to follow along with the Rails Console just to get used to using it.

The map method returns the result of applying the given block to each element in the array or range.

   I wish this was worded better
4.3.3 Hashes and symbols
Hashes are essentially arrays that aren’t limited to integer indices. (In fact, some languages, especially Perl, sometimes call hashes associative arrays for this reason.) Instead, hash indices, or keys, can be almost any object.
Very cool
 flash = { success: "It worked!", error: "It failed." }
 flash.each do |key, value|
   puts "Key #{key.inspect} has value #{value.inspect}"
 end
methods
  inspect
  p - p returns the object being printed while puts always returns nil
  map
  second - a rails method
  Hash merge http://www.ruby-doc.org/core-2.1.2/Hash.html#method-i-merge

strings vs. hashes
strings need to be compared character by character, while symbols can be compared all in one go.

When hashes are the last argument in a function call, the curly braces are optional
Exercises



Create three hashes called person1, person2, and person3, with first and last names under the keys :first and :last. Then create a params hash so that params[:father] is person1, params[:mother] is person2, and params[:child] is person3. Verify that, for example, params[:father][:first] has the right value.

instance method
A method called on an instance, such as length, is called an instance method.

class method
When a method gets called on the class itself, as in the case of new, it’s called a class method

Thursday, April 10, 2014

Notes - Rails Tutorial Chapter 2 & Ubuntu Updates

Did an upgrade of all my Ubuntu packages including Open SSL

OpenSSL could be made to expose sensitive information over the network, possibly including private keys.

Neel Mehta discovered that OpenSSL incorrectly handled memory in the TLS
heartbeat extension. An attacker could use this issue to obtain up to 64k
of memory contents from the client or server, possibly leading to the
disclosure of private keys and other sensitive information.

rails console vs irb

The exact prompt you'll see in irb can vary and I see the same one you do in Rails 3. It's nothing to worry about. In fact, I see the simple prompt in plain irb, and the full prompt in rails console :-)
They are both irb, it's just that rails console is set up such that the rails environment is all set and ready to work with, while regular irb has almost nothing loaded by default.

Controller

A controller is a Ruby class which inherits from ApplicationController and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the method with the same name as the action.

Request methods


An HTTP 1.1 request made using telnet. The requestresponse headersand response body are highlighted.
HTTP defines methods (sometimes referred to as verbs) to indicate the desired action to be performed on the identified resource. What this resource represents, whether pre-existing data or data that is generated dynamically, depends on the implementation of the server. Often, the resource corresponds to a file or the output of an executable residing on the server. The HTTP/1.0 specification[10]:section 8defined the GET, POST and HEAD methods and the HTTP/1.1 specification[1]:section 9 added 5 new methods: OPTIONS, PUT, DELETE, TRACE and CONNECT. By being specified in these documents their semantics are well known and can be depended upon. Any client can use any method and the server can be configured to support any combination of methods. If a method is unknown to an intermediate it will be treated as an unsafe and non-idempotent method. There is no limit to the number of methods that can be defined and this allows for future methods to be specified without breaking existing infrastructure. For example, WebDAV defined 7 new methods and RFC5789 specified the PATCH method.
GET
Requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect. (This is also true of some other HTTP methods.)[1] The W3C has published guidance principles on this distinction, saying, "Web application design should be informed by the above principles, but also by the relevant limitations."[11] See safe methods below.
HEAD
Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.
POST 
Requests that the server accept the entity enclosed in the request as a new subordinate of the web resource identified by the URI. The data POSTed might be, as examples, an annotation for existing resources; a message for a bulletin board, newsgroup, mailing list, or comment thread; a block of data that is the result of submitting a web form to a data-handling process; or an item to add to a database.[12]
PUT
Requests that the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, it is modified; if the URI does not point to an existing resource, then the server can create the resource with that URI.[13]
DELETE
Deletes the specified resource.
TRACE
Echoes back the received request so that a client can see what (if any) changes or additions have been made by intermediate servers.
OPTIONS
Returns the HTTP methods that the server supports for the specified URL. This can be used to check the functionality of a web server by requesting '*' instead of a specific resource.
CONNECT
Converts the request connection to a transparent TCP/IP tunnel, usually to facilitate SSL-encrypted communication (HTTPS) through an unencrypted HTTP proxy.[14][15] See HTTP CONNECT Tunneling.
PATCH
Is used to apply partial modifications to a resource.[16]
HTTP servers are required to implement at least the GET and HEAD methods[17] and, whenever possible, also the OPTIONS method.[citation needed]

Resources

A resource is simply the object the user of the application will interact with.

Rails Tutorial Chapter 8.20 

current_user=

First, you're reading the method names wrong (which is not surprising given how cryptic ruby method naming can be). def current_user=(user) is actually read as defining the method current_user= that takes an argument user, whereas def current_user defines a method current_user that takes no arguments. These are referred to respectively as setters and getters.

Setters and getters are like attr accessor and attr reader.

Thursday, November 7, 2013

Notes - Rails Tutorial Chapter 3.2 - Integration Tests vs. Unit Tests

Integration Tests vs. Unit Tests

Unit Tests

A unit test is a test written by the programmer to verify that a relatively small piece of code is doing what it is intended to do. They are narrow in scope, they should be easy to write and execute, and their effectiveness depends on what the programmer considers to be useful. The tests are intended for the use of the programmer, they are not directly useful to anybody else, though, if they do their job, testers and users downstream should benefit from seeing less bugs.   ~ Nathan Hughes

Integration Tests

An integration test is done to demonstrate that different pieces of the system work together. Integration tests cover whole applications, and they require much more effort to put together. They usually require resources like database instances and hardware to be allocated for them. The integration tests do a more convincing job of demonstrating the system works (especially to non-programmers) than a set of unit tests can, at least to the extent the integration test environment resembles production.
Actually "integration test" gets used for a wide variety of things, from full-on system tests against an environment made to resemble production to any test that uses a resource (like a database or queue) that isn't mocked out.

Thursday, October 17, 2013

Notes - Rails Tutorial Chapter 3.1

Sent PR to Bundler  hopefully it will get closed soon.
This fixes the issue: Warn if the same gem (same version) is added twice. bundler/bundler-features#22

To create the static views I am mainly in the app/controllers and the app/views directories

The config directory is where Rails collects files needed for the application configuration.

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
end

New in Rails 4
  • Previous versions of Rails used PUT in place of PATCH, and Rails 4.0 still supports this usage, but PATCH matches the intended HTTP usage better and is preferred for new applications. So GET, POST, PUT, DELETE is now GET, POST, PATCH, DELETE.

    Idempotence  is the property of certain operations in mathematics and computer science, that can be applied multiple times without changing the result beyond the initial application. It literally means "(the quality of having) the same power", from idem + potence (same + power).



Wednesday, October 16, 2013

Notes - Rails Tutorial Chapter 3.1 - Static Pages

I set the sample_app on GitHub and Herouku.

underscore method

Rails' ActiveSupport adds underscore to the String methods using the following code (This is NOT a String method in Ruby)

class String
  def underscore
    self.gsub(/::/, '/').
    gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
    gsub(/([a-z\d])([A-Z])/,'\1_\2').
    tr("-", "_").
    downcase
  end
end
underscore(camel_cased_word)
Makes an underscored, lowercase form from the expression in the string.

Changes ‘::’ to ‘/’ to convert namespaces to paths.

  'ActiveModel'. underscore    # => "active_model"
  'ActiveModel::Errors'.underscore    # => "active_model/errors"


As a rule of thumb you can think of it as the inverse of camelize, though there are cases where that does not hold:
'SSLError'
.underscore.camelize # => "SslError"

CREATE & DESTROY

$ rails generate controller FooBars baz quux
$ rails destroy controller FooBars baz quux
$ rails generate model Foo bar:string baz:integer
$ rails destroy model Foo
$ rake db:migrate
  We can undo a single migration step using
$ rake db:rollback
  To go all the way back to the beginning, we can use
$ rake db:migrate VERSION=0