14

Click here to load reader

Rails Concept

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Rails Concept

What is exciting about Rails ?

Ruby is known among programmers for a terse, uncluttered syntax that doesn’t require a lot of extra punctuation. Compared to Java, Ruby is streamlined, with less code required to create basic structures such as data fields. Ruby is a modern language that makes it easy to use high-level abstractions such as metaprogramming. In particular, metaprogramming makes it easy to develop a “domain specific language” that customizes Ruby for a particular set of uses (Rails and many gems use this “DSL” capability).

Ruby’s key advantage is RubyGems, the package manager that makes it easy to create and share software libraries (gems) that extend Ruby. RubyGems provides a simple system to install gems. Anyone can upload a gem to the central RubyGems website, making the gem immediately available for installation by anyone. The RubyGems website is where you’ll obtain the most recent version of Rails. And it is where you will obtain all the gems that help you build complex websites.

The design decisions that went into the first version of Rails anchored a virtuous circle that led to Rails’s growth. Within the first year, Rails caught the attention of prominent software engineers, notably Martin Fowler and Dave Thomas (proponents of agile software development methodologies). Rails is well-matched to the practices of agile software development, particular in its emphasis on software testing and “convention over configuration.” T

Convention Over Configuration

“Convention over configuration” is an example of Rails as “opinionated software.” It is an extension of the concept of a default, a setting or value automatically assigned without user intervention.

“Convention over configuration” means you’ll be productive. You won’t spend time setting up configuration files. You’ll spend less time thinking about where things go and what names to assign. And, because other developers have learned the same conventions, it is easier to collaborate.

Don’t Repeat YourselfKnown by the acrony DRY, “Don’t Repeat Yourself” is a principle of software development formulated by Andy Hunt and Dave Thomas and widely advocated among Rails developers.

Code reuse is a fundamental technique in software development. It existed long before Andy Hunt and Dave Thomas promoted the DRYprinciple. Rails takes advantage of Ruby’s metaprogramming features to not just reuse code but eliminate code where possible. With a knowledge of Rails conventions, it’s possible to create entire simple web applications with only a few lines of code.

There are many languages and frameworks available to build web applications, yet we chose to specialize in Ruby on Rails – so what is this all about? Ruby on Rails in web development provides both effective and efficient results of the highest possible quality. Here are some reasons why we are using Ruby on Rails at Zweitag since the first day and why we are still such big fans.

Page 2: Rails Concept

1 – Higher FlexibilityIn contrast to many other frameworks, Ruby on Rails facilitates to modify an application in response to customers needs, and not the other way around.

2 – Higher Development SpeedTrue to its maxime: don’t repeat yourself, quick development is especially facilitated by getting rid of repetitive coding. Consequently, development cycles in Rails are shorter than those in other programming languages.

3 – Agile Development at its bestFollowing a highly practical approach, where convention is set over configuration, Ruby on Rails enables and supports agile, lean software development and business development methods like The Lean Startup. As a result, going from planning to actual development can be done in shorter time-frames (rapid prototyping). Especially rich, complex projects profit from being more efficient by breaking down processes.

4 – Profit from Best Practices developed in big CommunityThe Ruby community is very active and passionate, thereby strengthening the technology itself by documenting, testing, enhancing and extending its features. There are many plugins and gems out there that help you to reuse software components and prevents you from repeating others work. The Rails community set many standards in web development. They pushed new technologies like REST, Unobtrusive Javascript, and so on. If you want to be the first using future technologies, you should use Rails.

5 – Multi Platform SupportRuby on Rails is available for all operating systems. The underlying programming language Ruby was ported to many platforms. WithJRuby we are able to run Ruby on Rails applications on Java Containers which enables us to deploy it in many enterprise environments.

6 - Industry support.There are professional hosting support companies, (Heroku, EngineYard). experienced consulting companies, two primary cloud-based offerings, and help with development and deployment and more. Both provide an easy-to-scale, managed hosting environment. Both are built on Amazon EC2 and offer contrasting approaches and features that will appeal to different audiences.Sphere Consulting is an 8+ year pioneer in Ruby on Rails development and expert in developing database-driven web applications.

Page 3: Rails Concept

All about performance optimization in Rails

There are many ways of how you can boost performance of Ruby On Rails applications. Approaches might be different and depend on the application structure, size of the database and traffic intensity but a general recommendation can also be given.

In this article we will overview techniques and architectural solutions that will help you to improve performance of your applications.

Use Caching

Rails provides three types of caching mechanisms out of the box which you can start using immediately. These are:

Page CachingA cached page served by the webserver without going through the Rails stack. It’s super fast but can’t be applied to every situation.The first time user requests /products, Rails will generate a file called products.html which will be passed to the next request by the webserver without invoking Rails.

Action CachingIt’s similar to Page Caching but the incoming request always goes through the Rails stack. It allows us to use authentication and other restrictions you can’t do with page caching.

Fragment CachingUnfortunately, caching the whole page is seldom possible when you’re developing dynamic web applications. But Rails provides a mechanism called Fragment Caching. It allows a fragment of view logic to be wrapped in a cache block and served out of the cache store when the next request comes in.

Rails has different stores for the cached data created by action and fragment caches. Page caches are always stored on disk. The default cache stores are MemoryStore, FileStore, DrbStore and Memcached store.

Rails uses the bundled memcached-client gem by default for Memcached store. Since Memcached supports clustering and load balancing it’s a great solution for scaling your application.

Keep in mind that caching always brings more complexity to the application and makes it harder to debug.

Database Optimization

Interacting with database is usually the slowest part of the application. Hopefully, there many things you can do to improve the performance:

Add all necessary indexes for primary and foreign keys and for fields used in conditions for filtering

Remove unused or ineffective indexes

Revise SQL queries and optimize them (use the EXPLAIN command)

Page 4: Rails Concept

Use eager loading of associations in Rails models

Don’t use transactions if they are not necessary (for example, in MySQL you can use MyISAM table engine which is much faster than InnoDB)

Use stored procedures

Denormalize some tables from 3-d form to 2-nd to avoid redundant joins

Perform partitioning for large tables

Cutting down the number of SQL queries is one of the many ways to improve the performance of your Rails application, and eager loading is probably the most effective way to do that.Eager loading comes into play when you need to eliminate “1+N” query problem: if you load N objects from class Article (table “articles”), which has a n-1 relationship to class Author (table “authors”), accessing the author of a given article using the generated accessor methods will cause N additional queries to the database. This, of course, puts some additional load on the database, but more importantly for Rails application server performance, the SQL query statements to be issued will be reconstructed for object accessed.You can get around this overhead by adding :include => :author to your query parameters

Scaling Out Your Database

There are two main approaches for addressing scalability through database clustering:

Database ReplicationIt’s used to address concurrent access to the same data. Database replication enables us to load-balance the access to the shared data elements among multiple replicated database instances. In this way we can distribute the load across database servers, and maintain performance even if the number of concurrent users increases.

There is a plugin for Rails called Masochism, which provides an easy solution for applications to work in a replicated database environment. It works by replacing the connection object accessed by ActiveRecord models by ConnectionProxy that chooses between master and slave when executing queries. Generally all rites go to master.

Page 5: Rails Concept

Database partitioning/sharding

Database shards/partitions enable the distribution of data on multiple nodes. In other words, each node holds part of the data. This is a better approach for scaling both read and write operations, as well as more efficient use of capacity, as it reduces the volume of data in each database instance.

Use third party solutions such as Apache Lucene/Solr or Sphinx to do full-text search against your database. These are very fast search engines that index data and provide flexible ways of searching it.

Use Load Balancing

Load balancing distributes requests over multiple Web or file servers, either within a centralized data center or distributed geographically, in order to avoid a situation where a single server becomes overwhelmed. The goal is to serve incoming requests at maximum speed, with maximum availability for a global user base.

Page 6: Rails Concept

Front-end optimization

Users spend a lot of time on waiting browser to finish downloading all page components such as images, style sheets, scripts, etc. Reducing the amount of components will minimize the number of HTTP requests which will lead to the faster page loading.

You can achieve this by combining style sheet files and JavaScript files as well as using CSS sprites and image maps.

To combine all CSS and JavaScript files into one in Rails, you can do by using the following commands:

You can go further and minimize combined files by using a gem called asset_packegerIt can also be a good idea to move images and videos to services like Amazon S3 or even use CDNs (Content Delivery Networks).

You can cache at the client side and use AJAX like Prototype and JQuery to stream in data to the browser on demand.Yahoo developed a Firefox plug-in called YSlow which gives you tips on how to optimize your page loading.

All about security in Rails

Page 7: Rails Concept

Authentication

Authentication is the foremost requirement of most of the web applications to authenticate and give privileges to their users. Apart from normal authentication mechanism rails have plugins for OpenID, CAS and Access Control. Build your own authentication system only if your requirements are very unique or you do not trust other implementations.

SQL Injection

The problem arises when metacharacters are injected into your queries to database. Rails has a very good support to avoid SQL injection if you follow conventions in issuing queries to your database.

Activerecord Validation

To validate the contents of model object before records are created/modified in the database. Activerecord validations are very useful over database data-type constraints to ensure values entered into the database follow your rules. You might have javascript validations for forms but javascript can easily be switched off. Use javascript validations only for better user experience.

Cross Site Reference(or Request) Forgery (CSRF)

In a CSRF attack, the attacker makes victim click on a link of his choice which would contain a GET/POST request and causes web application to take malicious action. The link could be embedded in a iframe or an img tag. Its recommended to use secret token while communicating with user to avoid this attack.

Minimize session attacks

If an attacker has session-id of your user, he can create HTTP requests to access user account. An attacker can get session-id by direct access to user machine or is able to successfully run malicious scripts at user machine. In this section we will talk about how to avoid or minimize the risk if attacker has user session-id. Following steps are helpful:

1.Store IP Address, but creates problem if user moves from one network to another.2.Create a new session everytime someone logs in.3.Expire session on user logout, user is idle for a time period or on closing of browser/tab. For maximum security expire sessions on all the three conditions.

Caching authenticated pages

Page caching does bypass any security filters in your application. So avoid caching authenticated pages and use action or fragment caching instead.

Cross site scripting(XSS) attack

Cross Site Scripting is a technique found in web applications which allow code injection by malicious web users into the web pages viewed by other users. An attacker can steal login

Page 8: Rails Concept

of your user by stealing his cookie. The most common method of attack is to place javascript code on a website that can receive the session cookie. To avoid the attack, escape HTML meta characters which will avoid execution of malicious Javascript code. Ruby on Rails has inbuilt methods like escape_html() (h()), url_encode(), sanatize(), etc to escape HTML meta characters.

Anti-spam form protection

Use Captcha or Javascript based form protection techniques to ensure only human can submit forms successfully.

When using Captcha do ensure the following :

1.Images are rendered on webpage using send_data and are not stored at the server, because its not required to store images and are redundant.2.Avoid using algorithm used by standard Catpcha plugins as they can easily be hacked, instead tweak an existing algorithm or write your own.3.Use a Captcha which does not store secret code or images in filesystem, as you will have trouble using Captcha with multiple servers.

Filter sensitive logs

Prevent logs of sensitive unencrypted data using #filter_parameter_logging in controller. The default behavior is to log request parameters in production as well as development environment, and you would not like logging of password, credit card number, etc.

Use password strength evaluators

A lot of people have used password strength evaluators simply because its used by google in their registration form. You can use it to help your users register with strong password. But I don't think its a must have security addon. Uptill now I have not found a good algorithm to assess strength of a password, but some of them are reasonable.

Also, if there is an open source tool or algorithm for evaluating password strength, it can easily be broken. So, you might consider tweaking the algorithm or building one from scratch.

Transmission of Sensitive information

Use SSL to encrypt sensitive data between transfer from client to server. SSL hits server performace, so you might consider using SSL only for few pages which transfer sensitive data to and from.

All about load balancing in Rails

Load balancing distributes requests over multiple Web or file servers, either within a centralized data center or distributed geographically, in order to avoid a situation where a single server becomes overwhelmed. The goal is to serve incoming requests at maximum speed, with maximum availability for a global user base.

Why is load balancing important?Under normal conditions, load balancing helps maximize available capacity and

Page 9: Rails Concept

performance of a given resource, including storage space and processor time. Effective load balancing can result in faster Web application performance, faster page loads, and consistent performance regardless of the user’s location.

Where load balancing becomes significantly more important is under conditions where a denial of service (DOS) or other attack occurs. Load balancing can play a role in mitigating the effects of such an attack by distributing the large volume of malicious traffic across multiple servers, data centers, and even continents. As part of an overall security strategy, this can maintain application performance and availability,thus allowing time for the isolation and blocking of attack traffic.

Effective load balancing strategies increasingly deploy application delivery controllers (ADCs) to help intelligently route application traffic and provide an additional layer of security.

In-house vs. Outsourced Load BalancingTraditional load balancing strategies are commonly referred to as ‘N+1’ approaches, where ‘N’ is the number of servers needed to manage a given amount of traffic, requests, or application demands, and ‘+1’ is the additional capacity added to provide headroom/failover in case demand exceeds supply of ‘N.’ This approach has obvious limitations; N+1 is still a finite resource, which can be vulnerable to both heavy legitimate traffic and increasingly common large-scale global attack traffic.

Consequently, organizations are leaving N+1 behind in favor of a more flexible, scalable approach made possible with a cloud-based load balancing solution. By accessing shared resources on a platform like Akamai’s global Intelligent Platform, organizations give themselves exponentially greater capacity to serve legitimate requests and mitigate the effects of large-scale attacks.

There are 3 main approaches:

Use load balancing solutions, e.g. HAProxy which supports a very high number of simultaneous incomming connections at very high speeds.

Use

partial processing on the main server and distribute workload to other servers after the initial processing. It can be done by 3 ways:

Redirect requests to servers over HTTP by their URLs

Page 10: Rails Concept

Use

messaging systems such as Active MQ, RabbitMQ, MQSeries

Use PgMQ client for

PostgreSQL with other AMQP systems

Use

dedicated servers for content distribution while logic is handled by the main server

Page 11: Rails Concept

How mobiloitte training has help you in last monthIt was a wondeful experience in mobiloitte. Mobiloitte training help me a lot to learn a new technology in a shorter period of time.

After the beginning of this HIV atlas Project , our seniors and the project manager explains the flows of whole application.

Our manager Jagdish sir is also very supportive since he always in meeting shared his experiences of different places he visited and encouraged us and simultaneously scolded us for not doing and not performing upto the expectation level.

The initial training timings were 7:30 am to 11 am in morning which should be whole day, may be we get more time to take help of our seniors.

At last, all seniors are helpful specially Himanshu Saxena. He helped me a lot at every stage.