Ruby
Updating ...
Learn Ruby on Rail with Kh@n.
Ruby is a language of careful balance. Its creator, Yukihiro “Matz” Matsumoto, blended parts of his favorite languages (Perl, Smalltalk, Eiffel, Ada, and Lisp) to form a new language that balanced functional programming with imperative programming.
He has often said that he is “trying to make Ruby natural, not simple,” in a way that mirrors life.
Building on this, he adds: Ruby is simple in appearance, but is very complex inside, just like our human body.
NOTE: Use Headphones and Click HD on video for better understanding.
Lecture #1
More Videos Are Uploading ....
Keep Visiting
khAn
Learn Ruby on Rail with Kh@n.
Ruby is a language of careful balance. Its creator, Yukihiro “Matz” Matsumoto, blended parts of his favorite languages (Perl, Smalltalk, Eiffel, Ada, and Lisp) to form a new language that balanced functional programming with imperative programming.
He has often said that he is “trying to make Ruby natural, not simple,” in a way that mirrors life.
Building on this, he adds: Ruby is simple in appearance, but is very complex inside, just like our human body.
NOTE: Use Headphones and Click HD on video for better understanding.
Lecture #1
More Videos Are Uploading ....
Keep Visiting
khAn
My 10 Favourite Things About The Ruby Language
1. Dynamic Typing
There are very good things about statically typed languages, such as compile-time verifiability and IDE support. However, in my experience, dynamic typing really helps get projects bootstrapped and smooth’s along changes, especially in the early to middle stages of a project.
I’m very happy that I don’t need to create a formal interface for my new objects to implement simply to enable me to easily swap out that class for another later on.
2. Duck Typing
This is effectively just an extension of Dynamic Typing. In Ruby, methods that expect to be able to operate on String objects don’t do checks for is_a?(String). They check whether the object respond to?(:to_str) and then calls to_str on the Object if it does. Similarly, objects that represent Paths in Ruby can implement a to_path method to provide the path representation.
In Rails, we use this technique for objects that have “model” characteristics by expecting them to respond_to?(:to_model). This allows us to support any object in relevant contexts, provided those objects can supply us with a “model” representation of themselves.
3. Awesome Modules
Ruby provides a language feature similar to “traits” in Scala, Squeak, and Perl. Effectively, Ruby modules allow the dynamic addition of new elements of the class hierarchy at runtime. The use of super is dynamically evaluated at runtime to take into consideration any modules that might have been added, making it easy to extend functionality on a superclass as many times as desired, without being forced to decide where super will land at class declaration time.
Additionally, Ruby modules provide the lifecycle hooks append_features and included, which make it possible to use modules robustly to isolate extensions from one another and to dynamically extend classes on the basis of feature inclusion.
4. Class Bodies Aren’t Special
In Ruby, class bodies aren’t a special context. They’re simply a context where self points at the class object. If you’ve used Rails, you’ve probably seen code like this:
class Comment < ActiveRecord::Base
validates_presence_of :post_id
end
|
It may look like validates_presence_of is a language feature, but it’s actually a method being called on Comment that is provided by ActiveRecord::Base.
That method can execute arbitrary code, also in the context of the class, including creating new methods, executing other pieces of code, or updating a class instance variable. Unlike Java annotations, which must be run at compile-time, Ruby class bodies can take runtime information into consideration, such as dynamically supplied options or the results of evaluating other code.
5. String Eval
This is likely a heresy. I’m not referring to arbitrary runtime String eval here, but rather String eval that is used to create methods early in the boot process of a Ruby application.
This can make it possible to take Ruby-defined structures, like Rails routes or AOP-definitions, and compile them into Ruby methods. Of course, it is possible to implement these things as add-ons to other languages, but Ruby makes it possible to implement these sorts of things in pure Ruby. It is, to a large degree, a self-hosting language.
6. Blocks and Lambdas
I’ve said this a few times and I’ll repeat myself: I don’t consider languages without anonymous lambdas to be powerful enough for me to use day-to-day. These constructs are actually extremely common, and found in languages as diverse as Ruby, JavaScript, Scala, Clojure, and of course Lisp.
They make it possible to implement block-scoped constructs that look like language features. The most common example usage is for File operations. In languages without lambdas, users are forced to use an inline “ensure” block every in the same lexical scope that they originally opened the file in, to ensure that the resource is closed.
In Java:
static void run(String in)
throws FileNotFoundException {
File input = new File(in);
String line; Scanner reader = null;
try {
reader = new Scanner(input);
while(reader.hasNextLine()) {
System.out.println(reader.nextLine());
}
} finally { reader.close(); }
}
|
Among other things, the Java version needs to wrap the creation of the Scanner in a try block so it can be guaranteed to be closed. In contrast, the Ruby version:
def run(input)
File.open(input, "r") do |f|
f.each_line {|line| puts line }
end
end
|
Because of the existence of blocks, it is possible to abstract away the need to close the File in a single location, minimizing programmer error and reducing duplication.
7. Combo Attack: Self-Hosting Language
The combination of several of the above features produce real-life examples of ways that we can “extend” the Ruby language in Rails. Consider the following:
respond_to do |format|
if @user.save
flash[:notice] = 'User was successfully created.'
format.html { redirect_to(@user) }
format.xml { render :xml => @user, :status =>ted, :location => @user }
else
format.html { render :action => "new" }
format.xml { render :xml => @user.errors, :status => :unprocessable_entity }
end
end
|
In this case, we’re able to seamlessly mix methods (respond_to) with normal Ruby code (ifand else) to produce a new block-scoped construct. Ruby’s semantics for blocks allow us toreturn or yield from inside the block, further blending the boundaries of the code-block and language constructs like if or while.
In Rails 3, we introduced:
class PeopleController < ApplicationController
respond_to :html, :xml, :json
def index
@people = Person.find(:all)
respond_with(@people)
end
end
|
Here, respond_to is provided at the class-level. It tells Rails that respond_with (in index) should accept HTML, XML, or JSON as response formats. If the user asked for a different format, we automatically return a 406 error (Not Acceptable).
If you dig in a bit deeper, you can see that the respond_to method is defined as:
def respond_to(*mimes)
options = mimes.extract_options!
only_actions = Array(options.delete(:only))
except_actions = Array(options.delete(:except))
mimes.each do |mime|
mime = mime.to_sym
mimes_for_respond_to[mime] = {}
mimes_for_respond_to[mime][:only] = only_actions unless only_actions.empty?
mimes_for_respond_to[mime][:except] = except_actions unless except_actions.empty?
end
end
|
This method is defined on the ActionController::MimeResponds::ClassMethods module, which is pulled into ActionController::Base. Additionally, mimes_for_respond_to is defined usingclass_inheritable_reader in the included lifecycle hook for the module. The class_inheritable_reader method (macro?) uses class_eval to add methods onto the class in question to emulate the built-in attr_accessor functionality.
Understanding all of the details isn’t important. What’s important is that using the Ruby features we described above, it’s possible to create layers of abstraction that can appear to add features to the Ruby language.
A developer looking at ActionController::MimeResponds need not understand howclass_inheritable_reader works–he just needs to understand the basic functionality. And a developer looking at the API documentation need not understand how the class-levelrespond_to is implemented–she just needs to understand the provided functionality. With that said, peeling back each layer leads to simple abstractions that build on other abstractions. There’s no need to peel back the whole curtain at once.
8. Nice Literals
I often forget about this when programming in Ruby, only to crash back down to earth when using a language with fewer, less expressive literals.
Ruby has literals for just about everything:
Strings: single-line, double-line, interpolated
Numbers: binary, octal, decimal, hex
Null: nil
Boolean: true, false
Arrays: [1,2], %w(each word is element)
Hashes: {key => value} and in Ruby 1.9 {key: value}
Regular expressions: /hello/, %r{hello/path}, %r{hello#{interpolated}}
Symbols: :name and :”weird string”
Block: { block literal }
And I think I’m missing some. While it may seem academic, good, readable literals can increase the programmer’s ability to write short but extremely expressive code. It’s of course possible to achieve the same sorts of things as you can with literal Hashes by instantiating a new Hash object and pushing the keys and values on one at a time, but it reduces their utility as method parameters, for instance.
The terseness of the Hash literal has allowed Ruby programmers to effectively add a limited keyword argument feature to the language without having to get approval by the language designers. Yet another small example of self-hosting.
9. Everything is an Object, and All Code is Executed and Has a self
I showed this to some degree earlier, but a lot of the reason that Class bodies work the way they do is a consequence of the unfailing object orientation of the Ruby language. Inside of a class body, Ruby is simply executing code with a self pointing at the class. Additionally, nothing is special about the class context; it is possible to evaluate code in a class’ context from any location. Consider:
module Util
def self.evaluate(klass)
klass.class_eval do
def hello
puts "#{self} says Hello!"
end
end
end
end
class PersonName < String
Util.evaluate(self)
end
|
This is exactly equivalent to:
class PersonName < String
def hello
puts "#{self} says Hello!"
end
end
|
By removing the artificial boundaries between code in different locations, Ruby reduces the conceptual overhead of creating abstractions. And this is the result of a strong, consistent object model.
One more example on this topic. This idiom is quite common in Ruby: possibly_nil && possibly_nil.method_name. Since nil is just an object in Ruby, sending it a message it does not understand will result in a NoMethodError. Some developers suggested the following syntax: possibly_nil.try(:method_name). This can be implemented in Ruby as follows:
class Object
alias_method :try, :__send__
end
class NilClass
def try
nil
end
end
|
Essentially, this adds the method try to every Object. When the Object is nil, try simply returns nil. When the object is not nil, try just calls the method in question.
Using targeted application of Ruby’s open classes, combined with the fact that everything in Ruby, including nil, is an object, we were able to create a new Ruby feature. Again, this isn’t such a big deal, but it’s another case where the right choices in the language can allow us to create useful abstractions.
10. Rack
I’m going to cheat a little bit since Rack isn’t part of the Ruby language, but it does demonstrate some useful things about it. First of all, the Rack library only hit 1.0 earlier this year, and already every single Ruby web framework is Rack compliant. If you use a Ruby framework, you can be guaranteed that it uses Rack, and any standard Rack middleware will work.
This was all done without any backward compatibility sacrifices, a tribute to the flexibility of the Ruby language.
Rack itself also leverages Ruby features to do its work. The Rack API looks like this:
Rack::Builder.new do
use Some::Middleware, param
use Some::Other::Middleware
run Application
end
|
In this brief code snippet, a number of things are at work. First, a block is passed to Rack::Builder. Second, that block is evaluated in the context of a new instance of Rack::Builder, which gives it access to the use and run methods. Third, the parameter passed to use and run is a class literal, which in Ruby is a simple object. This allows Rack to callpassed_in_middleware.new(app, param), where new is just a method call on the Class object Some::Middleware.
And in case you think the code to implement that would be heinous, here it is:
class Rack::Builder
def initialize(&block)
@ins = []
instance_eval(&block) if block_given?
end
def use(middleware, *args, &block)
@ins << lambda { |app| middleware.new(app, *args, &block) }
end
def run(app)
@ins << app #lambda { |nothing| app }
end
end
|
This is all that’s needed to implement the code I showed above the creates a new Rack application. Instantiating the middleware chain is a simple affair as well:
def to_app
inner_app = @ins.last
@ins[0...-1].reverse_each { |app| inner_app = app.call(inner_app) }
inner_app
end
def call(env)
to_app.call(env)
end
|
First, we take the last element from the chain, which is our endpoint. We then loop over the remaining elements in reverse, instantiating each middleware with the next element in the chain, and return the resulting object.
Finally, we define a call method on the Builder, which is required by the Rack specifically, that calls to_app and passes the environment through, kicking off the chain.
Through the use of a number of the techniques described in the post, we were able to create a Rack-compliant application that supports Rack middleware in under two dozen lines of code.
Subscribe to:
Posts (Atom)
0 comments:
Thanks you.