Highlights in Rails 4.2:
Active Job: It is a common interface on top of queuing systems like Resque, Delayed Job, Sidekiq, and more.
Asynchronous mails: Action Mailer now comes with a deliver_later method that sends emails via the queue, so it doesn't block the controller or model if the queue is asynchronous (the default inline queue blocks). Sending emails right away is still possible with deliver_now.
Adequate Record: It works by caching common SQL queries as prepared statements and reusing them on similar calls, skipping most of the query-generation work on subsequent calls.
Web Console: The Web Console is a gem , comes by default with 4.2 rails app. Web Console adds an interactive Ruby console on every error page and provides a console view and controller helpers.
Foreign key support: The migration DSL now supports adding and removing foreign keys. They are dumped to schema.rb as well.
=>delegate method in ruby on rails 3.2.13?
A.Delegation is particularly useful with Active Record associations:
class Greeter < ActiveRecord::Base
def hello
"hello"
end
def goodbye
"goodbye"
end
end
class Foo < ActiveRecord::Base
belongs_to :greeter
delegate :hello, :to => :greeter
end
Foo.new.hello # => "hello"
Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for #<Foo:0x1af30c>
=====================================
=>assets locations ?
Assets can be placed inside an application in one of three locations: app/assets, lib/assets or vendor/assets.
app/assets is for assets that are owned by the application, such as custom images, javascript files or stylesheets.
lib/assets is for your own libraries’ code that doesn’t really fit into the scope of the application or those libraries which are shared across applications.
vendor/assets is for assets that are owned by outside entities, such as code for JavaScript plugins.
Any subdirectory that exists within these three locations will be added to the search path for Sprockets (visible by calling Rails.application.config.assets.paths in a console). When an asset is requested, these paths will be looked through to see if they contain an asset matching the name specified. Once an asset has been found, it’s processed by Sprockets and then served up.
================================
=>How dynamic finders works?
A.using method_missing method
============================
=>Bi-directional Associations?
This happens because c and o.customer are two different in-memory representations of the same data, and neither one is automatically refreshed from changes to the other. Active Record provides the :inverse_of option so that you can inform it of these relations:
class Customer < ActiveRecord::Base
has_many :orders, inverse_of: :customer
end
class Order < ActiveRecord::Base
belongs_to :customer, inverse_of: :orders
end
With these changes, Active Record will only load one copy of the customer object, preventing inconsistencies and making your application more efficient:
c = Customer.first
o = c.orders.first
c.first_name == o.customer.first_name # => true
c.first_name = 'Manny'
c.first_name == o.customer.first_name # => true(:-with out inverse_of it would be false)
============================
=>What is difference between application.rb and environment.rb?
=config/environment.rb
This file is the common file required by config.ru (rails server) and Passenger. This is where these two ways to run the server meet; everything before this point has been Rack and Rails setup.
This file begins with requiring config/application.rb.
you could use it to have some special settings for your development stage, which are usefull for debugging.
=config/application.rb
This file requires config/boot.rb, but only if it hasn't been required before, which would be the case in rails server but wouldn't be the case with Passenger.
============================
=>rails server?
bin/rails =>application.rb
config/boot=>bundler
rails/commands=>
===========================
=>Alternative to localhost or 127...?
http://lvh.me:3000/
===========================
=>SEO?
alternatve to friendly_id
class Article < ActiveRecord::Base
def to_param
id.to_s+'-'+title.downcase.gsub(' ', '-')
end
end
===================================
=> form_for vs form_tag?
=>You would use form_for for a specific model,Form_tag create basic form
=>form_for prefers, as its first arg, an activerecord object; it allows to easily make a create or edit form to use it in a "new" view you should create an empty instance in controller, like:
It also passes a form variable to the block, so that you don't have to repeat the model name within the form itself. it's the preferred way to write a model related form.
form_tag just creates a form tag (and of course silently prepare an antiforgery hidden field, like form_for); it's best used for non-model forms (I actually only use it for simple search forms or the like).
================
options_from_collection_select vs options_for_select ?
form_for vs form_tag ?
update_attributes vs update_attribute ?
============
unlsess vs untill?
============
to set ist time?
2.seconds.in_time_zone(TZInfo::Timezone.get('Asia/Kolkata'))
============
Set session Expire time?
class ApplicationController < ActionController::Base
protect_from_forgery
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_path, :alert => exception.message
end
before_filter :verify_session
def verify_session
#raise session[:expire].inspect
if !session[:expire].nil? and session[:expire] < Time.now
# Session has expired. Clear or reset session.
reset_session
end
# Assign a new expiry time, whether the session has expired or not.
session[:expire] = 30.seconds.from_now.in_time_zone(TZInfo::Timezone.get('Asia/Kolkata'))
return true
end
end
==================
============
rails 4 features:
Turbolinks:-
it keeps the current page instance alive and replaces only the body and the title in the head.
https://github.com/rails/turbolinks/#asset-change-detection
Russian Doll Caching:-
The technique of nesting fragment caches to maximize cache hits is known as russian doll caching.
http://blog.remarkablelabs.com/2012/12/russian-doll-caching-cache-digests-rails-4-countdown-to-2013
Strong Parameters:-
Mass-assignment protection. Use attr_protected :is_admin in model to make not to allow user to hack from(by debugging) brwoser.
https://speakerdeck.com/maxsilver/strong-parameters-in-rails-4
Model A
attr_accessible :name, :email
attr_protected :is_admin
class A
def update
@person.update_attributes!(person_params)
end
private
def person_params
params.require(:person).permit(:name, :email)
end
end
=========================
========================
Fragment Caching: In order to address such a dynamically created page where different parts of the page need to be cached and expired differently, Rails provides a mechanism called Fragment Caching.
========================
=>symbolic gem?
if you want to get a simplified form of a big equation
if you want to speed up similar calculations
if you need an abstraction layer for math
Symbolic doesn't have any external dependencies.
==================
=>respond_to and respond_to? ?
Ruby treats ? and ! as actual characters in a method name. respond_to and respond_to? are different. ? indicates that this is going to respond with a true or false. Specifically:
respond_to? is a Ruby method for detecting whether the class has a particular method on it. For example,
@user.respond_to?('eat_food')
would return true if the User class has an eat_food method on it.
respond_to is a Rails method for responding to particular request types. For example:
def index
@people = Person.find(:all)
respond_to do |format|
format.html
format.xml { render :xml => @people.to_xml }
end
end
However, in the RailsTutorial link you've provided, you're seeing an RSpec method should interacting with RSpec's respond_to method. This wouldn't be available in your console, unless you run rails console test.
======================
=>ActiveSupport::concern
A.module M
def self.included(base)
base.extend ClassMethods
base.class_eval do
scope :disabled, -> { where(disabled: true) }
end
end
module ClassMethods
...
end
end
By using ActiveSupport::Concern the above module could instead be written as:
require 'active_support/concern'
module M
extend ActiveSupport::Concern
included do
scope :disabled, -> { where(disabled: true) }
end
module ClassMethods
...
end
end
==================
REMEMBER:
=========
=>models:
self.table_name
=>validations
absence ->present?
validates_with ->new class for validations
validates_each ->
=>callbacks
after_find
after_initialize
=>associations
inverse_of
association(force_reload = false)
association=(associate)
build_association(attributes = {})
create_association(attributes = {})
=>queries
find_each
find_in_batches ->to rertrievve bunch of records in array of models instead of one
User.find_each(start: 2000, batch_size: 5000) do |user|
NewsLetter.weekly_deliver(user)
end
except
unscope
plunk
=>migrations
reversable
revert
============================
Associations:
==========
belongs_to : each instance of the declaring model “belongs to” one instance of the other model.
has_one : each instance of a model contains or possesses one instance of another model.
has_many : each instance of the model has zero or more instances of another model.
has_many, :through : the declaring model can be matched with zero or more instances of another model by proceeding through a third model.
has_one,:through : the declaring model can be matched with one instance of another model by proceeding through a third model.
has_and_belongs_to_many-HABTM
The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the relationship model as an independent entity.
Polymorphic Associations:
=========================
=>a model can belong to more than one other model, on a single association
@employee.pictures
@product.pictures
If you have an instance of the Picture model, you can get to its parent via "@picture.imageable".
To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface
Self Join:
==========
class Employee < ActiveRecord::Base
has_many :subordinates, :class_name => "Employee",
:foreign_key => "manager_id"
belongs_to :manager, :class_name => "Employee"
end
With this setup, you can retrieve @employee.subordinates and @employee.manager.
==============
Explain ajax call in ror?
http://guides.rubyonrails.org/ajax_on_rails.html
=>request.xhr? indicates the controller has
received an ajax request. It returns true or false
We do request.xhr? only to check the request type, either
its AJAX request or others(post, get).
XMLHttpRequest
======================
ajax request:
============
$.ajax({
type: "GET",
url: "/sort?" + $.tableDnD.serialize(),
success: function(){
...
}
});
or
$.ajax({
type: "POST",
url: "/sort",
data: $("tr", "$admintabel").map(function(){
return this.id;
}),
success: function(){
...
}
});
var loaded = false;
$(".mySection").mouseenter(
if(!loaded){
function(){
$.get("URL FOR AJAX", function(data){loaded = true; /*do stuff with data*/});
});
}
$.ajax({
type: 'POST',
url: "/answers/" + window.questions[question_number].answers[answer_number].id + "/update",
data: { answer: window.questions[question_number].answers[answer_number] }
});
==============
RAILS 3.1 FEATURES:=
1)Asset Pipeline:-
==================
To concatenate and minify or compress JavaScript and CSS assets.
manifest is app/assets/javascripts/application.js:
features:
=========
->it reduces the number of requests that a browser must make to render a web page
->For CSS, this usually involves removing whitespace and comments. For JavaScript, more complex processes can be applied
->the ability to code these assets using another language, or language extension. These include Sass for CSS, CoffeeScript for JavaScript, and ERB for both.
Fingerprinting:
===============
global.css => global-908e25f4bf641868d8683022a5b62f54.css
When the content is updated, the fingerprint will change and the remote clients will request the new file. This is generally known as cachebusting.
2)HTTP Streaming :-
===============
This lets the browser download your stylesheets and JavaScript files while the server is still generating the response.
3)jQuery is now the default:-
===========================
4)Reversible migrations:-
========================
def change
end
5)Mountable engines:-
====================
6)Identity Map:-
================
An identity map keeps a collection of previously instantiated records and returns the object associated with the record if a request is made for it again
which will avoid creating tons of single use objects which then have to be collected.
7)Prepared statements:-
=======================
The benefit to prepared statements is that the database does not have to compile a query plan for every piece of SQL sent to it, potentially saving a lot of time.
==============
Caching with Rails:
===================
=>page catching:-Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the webserver (i.e. Apache or nginx), without ever having to go through the Rails stack at all.
=>action catching:-One of the issues with Page Caching is that you cannot use it for pages that require to restrict access somehow. This is where Action Caching comes in.
=>Fragment Caching:-In order to address such a dynamically created(different users with different contents) page where different parts of the page need to be cached and expired differently, Rails provides a mechanism called Fragment Caching.
=>Sweepers:-Cache sweeping is a mechanism which allows you to get around having a ton of expire_{page,action,fragment} calls in your code.
=>SQL Caching:-
=>Cache Stores:-
config.cache_store = :memory_store
ActiveSupport::Cache::Store
ActiveSupport::Cache::MemoryStore
config.cache_store = :memory_store, :size => 64.megabytes
config.cache_store = :file_store, "/path/to/cache/directory"
ActiveSupport::Cache::MemCacheStore
config.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.com"
centralized cache for your application. Rails uses the bundled memcache-client gem by default
config.cache_store = :ehcache_store < jruby-ehcache-rails3 gem required.>
config.cache_store = :null_store
config.cache_store = MyCacheStore.new
Rails.cache.read(:site => "mysite", :owners => [owner_1, owner_2]) # This is a legal cache key
Conditional GET support
=================
Q)Delete Vs. Destroy In Rails?
A)
=>Destroy on the other hand allows for a few more options. First, it will check any callbacks such as before_delete, or any dependencies that we specify in our model. Next, it will keep the object that just got deleted in memory; this allows us to leave a message saying something like “Order #{order.id} has been deleted.” Lastly, and most importantly, it will also delete any child objects associated with that object!
============
Q)for vs each?
A)each scopes block variable inside the block, whereas for/in scopes it outside the block.
============
=>ActiveRecord::Base:-The Base class(is a class of ActiveRecord Module) is commonly used to identify an abstract class, intended to be extended and implemented in a concrete class by the developer
For instance, ActiveRecord::Base is the abstract class for any Active Record model in a Rails project. A model looks like
class User < ActiveRecord::Base
end
Likewise, Observer defines its own Observer::Base and Action Controller defines ActionController::Base which, in a Rails project, is immediately implemented by ApplicationController::Base.
Ruby doesn't provide and language-level keyword or syntax to define abstract classes. Technically speaking, ActiveRecord::Base it's not a real abstract class, but it's a kind of convention to use Base for this pattern
============
The session id is a 32 byte long MD5 hash value
Turbolinks:
===========
Turbolinks also uses pushState,(same as PJAX) but instead of replacing only parts a page it loads a complete website from the server and replaces the <title> and <body> in the currently loaded DOM.
gem 'turbolinks'
<a href="/articles" data-no-turbolink>Articles</a>
app/assets/javascripts/application.js:
//= require turbolinks
Redis:
======
=no need of database.yml
http://jimneath.org/2011/03/24/using-redis-with-ruby-on-rails.html
Redis is an extremely fast, atomic key-value store. It allows the storage of strings, sets, sorted sets, lists and hashes. Redis keeps all the data in RAM, much like Memcached but unlike Memcached, Redis periodically writes to disk, giving it persistence.
Redis is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets.
You can run atomic operations on these types, like appending to a string; incrementing the value in a hash; pushing to a list; computing set intersection, union and difference; or getting the member with highest ranking in a sorted set.
In order to achieve its outstanding performance, Redis works with an in-memory dataset. Depending on your use case, you can persist it either by dumping the dataset to disk every once in a while, or by appending each command to a log.
gem 'redis', '2.1.1'
Lastly, create an initializer in config/initializers/redis.rb and add the following:
$redis = Redis.new(:host => 'localhost', :port => 6379)
Multiple Databases:
==================
# model in the "default" database from database.yml
class Person < ActiveRecord::Base
# ... your stuff here
end
# model in a different database
class Place < ActiveRecord::Base
establish_connection (
:adapter => "mysql",
:host => "other_host",
:username => "username",
:password => "password",
:database => "other_db"
)
end
activemessaging 0.12.1:
======================
ActiveMessaging is an attempt to bring the simplicity and elegance of rails development to the world of messaging. Messaging, (or event-driven architecture) is widely used for enterprise integration, with frameworks such as Java's JMS, and products such as ActiveMQ, Tibco, IBM MQSeries, etc. Now supporting Rails 3 as of version 0.8.0.
class HelloWorldProcessor < ActiveMessaging::Processor
subscribes_to :hello_world
def on_message(message)
puts "received: " + message
end
end
========================
============================================================================================================
3 =>select_tag(ksadf,options_for_select()) /when no model
3 =>select(@person, :city_id, options_for_select()) /when association
3 =>options_from_collection_for_select(City.all, :id, :name) /model id name
collection_select combines select_tag with options_from_collection_for_select.
5=> collection_select(:person, :city_id, City.all, :id, :name) #association with id,name model
=>To recap, options_from_collection_for_select is to collection_select what options_for_select is to select
=>Pairs passed to options_for_select should have the name first and the id second, however with options_from_collection_for_select the first argument is the value method and the second the text method.
========================
content_for in layouts?
yield is how you specify where your content areas is going to go within a layout. You might have something like this:
<div>
<h1> This is the wrapper!</h1>
<%= yield :my_content %>
</div>
content_for is how you specify which content is going to be rendered into which content area. You might have something like this:
<% content_for :my_content do %>
This is the content.
<% end %>
The result would be
<div>
<h1> This is the wrapper!</h1>
This is the content.
</div>
They are opposite ends of the rendering process, with yield specifying where content goes, and content_for specifying what the actual content is.
Is there a generally accepted best practice?
The best practice is to use yield in your layouts, and content_for in your views. There is a special second use for content_for, where you give it no block and it returns the previously rendered content. This is primarily for use in helper methods where yield cannot work. Within your views, the best practice is to stick to yield :my_content to recall the content, and content_for :my_content do...end to render the content.
========================
Turbolinks:
==========
Instead of letting the browser recompile the JavaScript and CSS between each page change, it keeps the current page instance alive and replaces only the body and the title in the head. Think CGI vs persistent process.
Webservices:
============
http://searchsoa.techtarget.com/tip/REST-vs-SOAP-How-to-choose-the-best-Web-service
=SOAP has a lot of overhead when sending/receiving packets since it's XML based, requires a SOAP header, etc. REST uses the URL + querystring to make a request, and thus doesn't send that many kB over the wire.
=SOAP requires an XML message to be parsed and all that <riduculouslylongnamespace:mylongtagname>extra</riduculouslylongnamespace:mylongtagname> stuff to be sent and receieved.
REST usually uses something much more terse and easily parsed like JSON.
https://www.computersnyou.com/3223/install-ruby-ubuntu-14-04-via-source-via-rvm/
No comments:
Post a Comment