Step-By-Step Guide to Building Your First Ruby Gem


Step-By-Step-Guide-to-Building-Your-First-Ruby-Gem.png

Nowadays all the functionalities in Rails are built as Ruby gems. For example we can use devise gem for the authentication part of the application. It’s like a package or library that is written in Ruby programming language. Moreover it can be imported and used by others in their programs.

Step 1
Bundler is like a dependency management tool for Ruby, which is also used by Rails. We will use Bundler for the basic gem structure. It helps us to install the correct versions of the gem and forces us to use the same in the application. So the command for that is, gem bundler install
After bundling, we should specify the gem “name” that we are going to create i.e. Bundle gem “testgem” will create a repository shown below

ruby-gem - Step-By-Step Guide to Building Your First Ruby Gem
So in this we can see the basic gem structure. Under the lib folder, version file will be used to mention the version of the Gem. We can edit the version as per our convenience and release it that will be the version in Rubygems.

rubygem - Step-By-Step Guide to Building Your First Ruby Gem

Step 2
We will consider testgem.gemspec, with testgem as the name of the gem that we will create for sample. It will be used to set up the gem on rubgems, for e.g., name of the gem, summary, description, files that are required in this project, test files that are used to testing the files in the project etc.

ruby-gem-1 - Step-By-Step Guide to Building Your First Ruby Gem
Rake file: – This makes releasing the new versions of the gem, and also helps other developers to check the test cases if they are going to modify the particular gem.
After the rake, we should create a test folder and test cases for each segments will be included here in the app directory.

Step 3
Planning to make a rubygem, then we need to analyse the requirements what to build up and what all functionalities should be included in that.
While generating, we should create a sample.rb file inside lib folder and create own class with namespace because the other plugin has also the same classes then it will get conflict in the names. And require the sample.rb file in the testgem.rb file like reqiure “testgem/sample”.

Step 4
We have require “bundler/gem_tasks” in rake file so when we run rake release, it will release the gem to ruby gems and make it available. Push to git repository

RubyGems are commonly used in Applications
1) Rails – Rails is a ruby gem
2) Better Errors / Rails Footnotes – Debugging tools for Rails/Rack apps.
3) Resque / Delayed Job / Sidekiq – Used for creating background jobs, placing them on multiple queues, and processing them later.
4) Cancan / Devise – Authorization / Authentication Gems for Ruby on Rails.
5) Letter Opener – Test your emails within the browser itself.
6) Discourse – Discussion Forum.
7) Carrierwave / Paperclip – Classy solutions for file uploads for Rails.
8) Whenever – Cron jobs (scheduled tasks) in Ruby.
9) Thin / Unicorn / Puma – Web servers.

RailsCarma provide end to end Ruby on Rails Development services including, consulting, architecture, building, management and extension to companies around the globe. You can also hire Ruby on Rails developers with an easy to hire process. Contact us to know more.

Application API with Ruby on Rails


application-api-with-ruby-on-rails

What is an API? Why API in ROR?
An API is an application programing interface. It’s an interface between inside and outside where outside interact with inside using codes. So the inside could be a server or devise like mobile, IPad, software libraries like Ruby on Rails, JQuery etc., interacting with HTTP through the web.
API’s are built as a component of the application. Basically we need to have a web API if we want to store and process our data in server and let any other application (web application, mobile application, iOS devices etc.) request and get data from that server if needed. These other applications can be part of your system or you can open your data for others to use.

Advantages of Building an API
We can separate the front end into Angular JS, Ember JS, or other popular client frameworks for building customized UI.

Advantages :

  • Lots of flexibility
  • Lower maintenance cost
  • Higher scalability
  • Simplicity
  • API development also allows you to easily integrate other user interfaces, which saves a lot of time.

Disadvantages of building an API

  • Since the coder is sending message repeatedly with redundant information, it adds up to the bandwidth.
  • Negligible latency
  • Use of headers is clumsy and ties the API to HTTTP Response.

REST API in Rails
Representational state Transfer convention for Hadoop developed in Web.is the software architectural style for the web. The architecture is used for giving flexibility to retrieve data through some endpoints. It runs over HTTP protocol.

How does one makes an API REQUEST?
URL = HTTP, HOSTNAME, URI
E.g. URL: -https://portal.ehealthpro.com/blogs

     Screenshot-from-2016-07-05-092406 - Application API with Ruby on Rails           Screenshot-from-2016-07-05-092406 - Application API with Ruby on Rails                    Screenshot-from-2016-07-05-092406 - Application API with Ruby on Rails

Protocol       SERVER              URI

Each resource has two URI’s, one represents the collections of the list i.e., https://portal.ehealthpro.com/blogs and other represents the item, i.e. it represents the single item in that collection   https://portal.ehealthpro.com/blogs/12
For building an API, We can use the Gem called “gem rails-api”
https://github.com/rails-api/rails-api , Generally, API needs to respond to uniform resource identifier (URI) and HTTTP. So,

In Routes,

Rails-Development-1 - Application API with Ruby on Rails

Namespaces

Rails generator create a Userscontroller and related routes specs. In the above routes, by defining a namespace under the routes.rb file, Rails will automatically map that namespace to an index coordinating the name under the controllers folder, the api/ directory. And the response we are acheiving via JSON format, so we just need to specify this format as the default one. Setting the API under a subdomain due to escalate the application to a DNS level.
And path option is to set the starting path for any request to be root in relation to the subdomain.

Versioning

Versioning the  application provides the basic structure to the API, and also when changes needs to be  done then we  can give developers the opportunity to adapt for the new features while old ones are being deprecated. In order to set the version for the API, we first need to add another directory under the API we created i.e. “v1”.we can add scope our API into different versions according to our convenience.

Scope module: :v1,
Constraints: ApiConstraints.new(version: 1, default: true) do
………
End

Generating the Controller
Command use to generate the User controller, rails generate controller API:: v1::users

In controller we need to do the requests respond with JSON data, Technically JSON is a lightweight data-interchange format, a collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
In rails, there is a gem called Active model serializer for implementing the JSON response. By using this gem we will get the proper format of the JSON.
Active Model Serializer is a great way to build JSON responses using an object oriented approach. The objects have a very similar feel on how your ActiveModel object is set up in terms of attributes and relationships. It likewise permits you to pick your connector to decide what type of JSON structure is produced-or to build your own.

railsdeveloment2 - Application API with Ruby on Rails

HTTP Status code, is just way to uniformly tell the person what the respond is, whether the response shows error or not.
And some of the status code are,
200 – OK , Successful Get
204 – No content, Successful Delete or Post
201 – Created – Successful Post
422 – Unprocessable Entity
401- Unauthorized, Authentication Failure

SECURITY
For the security reason in our API application, we can use HTTPS,
Rails.application.configure do
config.force_ssl = true
end

Finally,Testing the API,S
comand line: – curl or htttpie
Browser: – Postman, JSON-Formatter
Rspec :- Request Specs
Rails Minitest :- Integration tests

RailsCarma has been providing ruby on rails development and consulting services from past 8 years Our developers are well versed in doing all kinds of ruby on rails development work and handling any kind of project. Contact us to know more about our development skills and the projects which we can handle.

Source: Application API with Ruby on Rails

Splitting Monolithic Rails Application to Microservices


As a business gets bigger, they require more functionalities and thus you can’t help but add new models/controller to the existing Rails application and sometimes it becomes a monolith. If you are facing a monolith application which has become unmaintainable and difficult to deploy, you need to know some ways to manage it. If your team has to go through thousands of lines in order to understand the project and to make some changes, it is time to split them.

When to split application

  • When your tests run for more than 20 minutes.
  • Models grown to several hundred or thousands.
  • Independent functionality.
  • When developers cannot work independently to develop/deploy their own modules.

Different ways to split Monolithic application

  • Using microservices.
  • Using ‘faster’ technologies.
  • Add a bunch of servers.

What is microservice                                                                                                                                           Microservices is a strategical way for decomposing a large project into smaller, more manageable pieces. A microservice is a piece of application functionality re-factored out into its own code base, speaking to other microservices over a standard protocol. To accomplish this, first divide your business requirements into related groups like user management logic, advertising logic, and a web user interface.

Why microservice
The first force that led to the surge in microservices was a reaction against normal monolithic architecture. While a monolithic app is One Big Program with many responsibilities, microservice-based applications are composed of smaller programs, each with a single responsibility. This allows teams of devs to work independently on different services. The inherent decoupling also encourages smaller, simpler programs that are easier to understand, so new devs can start contributing more quickly. Finally, since no single program represents the whole of application, services can change direction without massive costs. If new technology becomes available that makes more sense for a particular service, it’s feasible to rewrite just that service. Similarly, since microservices communicate across a different languages, an application can be composed of several different platforms – Ruby, Java, PHP, Node, Go, etc without any issue.

Advantages

  • Modules can be reused.
  • Deployment goes smoothly independent of whole big application.
  • Easy to add features.
  • Reduces testing time to test one module instead of all.
  • Big applications tend to be harder to maintain that the small ones.
  • Having set of small applications allows us to focus on working on isolated parts.
  • We might have more chance of not breaking other parts of the application.
  • Reliability and fault tolerance.
  • Easy to migrate or upgrade.
  • Technology diversity.
  • If any single application function is not working entire application doesn’t goes down.
  • Makes it easier for a new developer to understand the functionality of a service.

Disadvantages
Because everything is now an independent service, you have to handle requests carefully travelling between your modules. There can be a scenario where any of services may not be responding.
Multiple databases and transaction management can be painful.
Productivity will be less till the microservice base is set.

Monolithic v/s Microservices
The below diagram shows the difference between traditional monolithic app and microservices in terms of human resource, time, maintenance and handling complexity of applications.

image - Splitting Monolithic Rails Application to Microservices

How to set up microservices
Strategical how to shrink the monolithic application is to split the layers like presentation, business logic and data access layers. A typical enterprise application consists of at least three different types of components:

  • Presentation layer – Components that handle HTTP requests and implement either a (REST) API or an
    HTML-based web UI. In an application that has a sophisticated user interface.
  • Business logic layer – Components which are the core of the application where business rules are implemented.
  • Data-access layer – Components having access to infrastructure components such as databases and message brokers.

RailsCarma has been implementing Ruby on Rails applications from its nascent stages for development, training, deploying and contributing back to the Rails Community. Through trusted technical expertise and consummate customer service combined to deliver a delightful experience for clients, RailsCarma provide end to end Ruby on Rails Development ,consulting, architecture, management and extension to companies around the globe. Contact us to know more.

Source : Splitting Monolithic Rails Application to Microservices

Charts In Rails


We have been working on a project that deals with server data where charts are worth a thousand words. I always get requests for various charts and in the past I’ve used Gruff to produce them. Gruff is a great library and the results look good too! However, recently I’ve have had more demanding requirements to provide more dynamic behavior on the charts. Users wanted to be able to interact with the charts in various ways and drill down to gather more information.

I looked at the alternatives to Gruff and decided to go with XML/SWF charts. These frameworks use Flash rendering for charts and have great features, 24hr turn around support and they’re inexpensive. The other advantage is that we no longer had to deal with figuring out the various spells to install RMagick on client’s servers. Moreover, we were able to delegate the actual chart rendering over to the client, which with dynamic graphs is key. All we had to do now on the server side was generate XML (for CPU usage in real time).

In this article, I would like to throw some light on various charts that are available for rails like Gruff, Google charts, Ziya charts, Open Flash charts and Fusion charts.

I am currently using Open Flash charts for the current project.

Gruff charts:
Gruff is a Ruby library for generating attractive and powerful graphs, useful for web applications, print media and many others.

Snapshot Rendering

You can render a Gruff graph as many times as you want and change any settings between renders. Data, colors, even the graph size and image type can all be changed for the next render.

Easily Extensible

Gruff is designed to be extremely extensible. Adding new graph types or themes can be done in as little as a few lines of code. If you need more control over your graphs, you can customize the layouts, data generation, almost anything.

Installaton

sudo gem install gruff


Demonstration of usage

Pie Chart example

require ‘rubygems’

require ‘gruff’

g = Gruff::Line.new

g.title = “My Graph”

g.data(“Apples”, [1, 2, 3, 4, 4, 3])

g.data(“Oranges”, [4, 8, 7, 9, 8, 9])

g.data(“Watermelon”, [2, 3, 1, 5, 6, 8])

g.data(“Peaches”, [9, 9, 10, 8, 7, 9])

g.labels = {0 => ’2003′, 2 => ’2004′, 4 => ’2005′}

g.write(‘my_fruity_graph.png’)

Google charts:

The Google Chart API returns a PNG-format image in response to a URL. Several types of image can be generated, including line, bar, and pie charts. For each image type, you can specify attributes such as size, colours, and labels.

Installation ruby script/plugin install http://google-charts-on-rails.googlecode.com/svn/google_charts_on_rails/

Once installed, start using it directly in your project.

Pie Example

GoogleChart.pie(10,20,40,30).to_url

With labels:

GoogleChart.pie([‘1997’,10],[‘1998’,20],[‘1999’,40],[‘2000’,30]).to_url

Ziya Charts:

Ziya allows you to easily create interactive charts, gauges and maps for your web applications. Ziya leverages flash which offloads heavy server side processing to the client. At the root, Ziya allows you to easily generate an XML files that will be downloaded  for rendering. Using this gem, you will be able to  create great looking charts for your application easily.

Features :
-Supports a wide variety of chart/gauge types.
-Geographical maps.
-Relieves your server load by generating the actual chart on the client side.
-Themes support. You can change the appearance and behavior of any charts by introducing new themes.

Installation :
> gem sources -a http://gems.github.com
> sudo gem install derailed-ziya

cd to your application directory and issue the following command:
> ziyafy –charts
This will copy the necessary themes and flash files to run ZiYa in your application’s public/charts directory. You can install maps and gauges components as well. Type in:

> ziyafy –help
To see all available options.

Open Flash Charts:

Features :
-More dynamic graphs with eye catching tooltips and legends for readability.
-Various types of charts available, except real time charts.
-Simple and easy to install the plug-in. Does not need and gem like Rmagick or ImageMagick.
-Data is rendered and displayed in SWF format.
To install and use the open flash chart plug-in for Rails do the following:

1.script/plugin install http://svn.pullmonkey.com/plugins/trunk/open_flash_chart/
2.Move the open_flash_chart.swf file into your RAILS_ROOT/public directory
3.Move the swfobject.js file into your RAILS_ROOT/public/javascripts directory
4.Create a controller and a view as in my examples below.

Implementation:
def index_stacked_bar
@graph = open_flash_chart_object(600,300,”/test_it/graph_code_stacked_bar”)
end

def graph_code_stacked_bar
title = Title.new(“A stacked bar chart”)
title.set_style( “{font-size: 20px; color: #F24062; text-align: center;}” );
bar_stack = BarStack.new
bsv1 = BarStackValue.new(2.5, ‘#C4D318′) # yellow
bsv2 = BarStackValue.new(5, ‘#50284A’) # purple
bsv3 = BarStackValue.new(1.25, ‘#7D7B6A’) # gray
bsv31 = BarStackValue.new(1.25, ‘#C4D318′) # yellow
bar_stack.append_stack( Array.new( [bsv1, bsv2, bsv1 ]) ); # 0
bar_stack.append_stack( Array.new( [bsv1, bsv2, bsv3,bsv31 ]) ); # 0
bar_stack.set_tooltip( ‘X label [#x_label#], Value [#val#]<br>Total [#total#]‘ );
y = YAxis.new();
y.set_range( 0, 14, 2 );

x = XAxis.new();
x.set_labels_from_array( Array.new( [‘Winter’, ‘Spring’, ‘Summer’, ‘Autmn’ ]) );
tooltip = Tooltip.new;
tooltip.set_hover();
chart = OpenFlashChart.new
chart.set_title(title)
chart.add_element(bar_stack)
chart.x_axis = x ;
chart.y_axis = y ;
chart.set_tooltip( tooltip );
render :text => chart.to_s
end

Fusion Charts:

Fusion Charts is a flash-based charting component which can generate interactive and animated charts. Fusion Charts can be used with any web scripting language, to deliver powerful charts with fairly minimal coding. Fusion Charts comes with wrapper modules for use with RoR.
Fusion Charts offers over 45 types of 2D/3D charts including line, area, bar, column, pie, doughnut (donut), combination, scatter, bubble, scroll charts etc. The functional and cosmetic aspects of each chart can be extensively customized using the XML API used by Fusion Charts.
Generating charts using Fusion Charts in Ruby on Rails through a sample application. To run the sample application, the following would be needed:
• FusionCharts Free/ v3:
Fusion Charts Free can be downloaded by clicking here

or the commercial version with more options can be downloaded directly from www.fusioncharts.com .

Installation of Fusion Charts involves just copying and pasting the SWF and .rb files from the download package into appropriate application folder. The .rb files are present in Download Package > Code > RoR > Libraries folder.
• Ruby 1.8.6 or above
• Rails gem 2.0.2 or above:
• MySQL 4.0 or above

All the charts explained above have its own advantages and disadvantages. The best way to use them depends on the type of the requirements of your project. Hope this article helps to implement the best use of the charts available in rails.

Source : RailsCarma

How To Build The Perfect Team?


Without doubt one of the main tasks of a startup CEO , is to create a dream team that will be in a position to get the entire startup off the ground. Nobody can reach ambitious objectives by themselves . With the greatest share of duties before the future team , investors , clients and/or consumers , business leader should have someone to depend on . These people will communicate personally as well as talk about business challenges . They will put forth proposals and make decisions , affect the company culture , as well as develop the environment by themselves . If we step aside from ‘be motivating , be a good example , and have passion for what you do’ advice , we’ll find out several more efficient tips you should always take into account .

1 . Become an HR manager yourself
You need to know the right person from wrong . An HR manager can assist you to evaluate the professional experience and approach of a candidate , but it’s you who is required to feel whether or not this is the person you want to work with . Selecting the core of the team is the duty that begins with you .

2 . Seek the services of the best professionals there are
This is certainly the main rule – seek the services of individuals with experience in different areas . They are more expensive and it’s more difficult to wake and sustain their interest , however the effectiveness of work as well as their efforts will take care of salary expenses . It would also be a lot less important to manage each and every of their efforts . Employing a ‘so-so’ professional may in the long run result in a need for replacement , so why not stop it right away ?

3 . Offer challenges
Money is an excellent motivator , but could possibly be not the perfect one . On many occasions experienced professionals do not have a problem looking for a job , and therefore they would like an ideal chance for self-actualization instead of a small salary improvement . Ambitions , along with non-standard , challenging , creative tasks , can play a pivotal role in establishing a startup .

4 . Bring home a diversity of individuals
Members of your team don’t have to have the same age , gender , character traits , ethnicity , whatever . A diverse traits along with experience , professionalism as well as shared vision of powerful personalities , is a solid , effective backbone for the team .

5 . Search for individuals with triumphs
No matter what these achievements are , whether they concern your area of expertise or not . This demonstrates a person’s commitment to the things they like and enjoy doing . Later on they need to possess all the needed circumstances to take pleasure in their work , along with wish to set goals , do their best , and be successful – just like they did before .

6 . Never hire full-time by reason of urgency
You could possibly just end up eventually searching for an alternative . The waste of your time and money can be eliminated by offering a one-time quantity of work . Or perhaps you will be lucky to quickly find the person you need – who knows .

7 . Set the mission of your company endeavor , shared vision , values and goals .
You should agree on what you would like to achieve and the ways you will be achieving it .

8 . Be clear with expectations and goals , and encourage teamwork
Clearly define responsibilities of every team player . However , do not isolate anyone ( this concerns a single person , as well as a whole department ) to make them concentrate on their own duties only . Teamwork is always far more effective . Specialists in different areas ( a CEO , a technical specialist , a marketing manager , whoever else ) will make contributions to solving common business tasks – for a startup it’s an optimal solution from the very beginning .

9 . Be patient to mistakes
If a person repeatedly makes the same mistakes , unable to analyze and improve the outcome of work , maybe that’s not the person you have been looking for . But in general everyone makes mistakes , including you , and the best thing is to learn from them , and solve problems together .

10 . Help people develop their skills
This will boost the performance of the whole team in the end . Practice brainstorming of ideas and never let anyone rest on laurels.

Source : RailsCarma

Ruby on Rails Developer For your Web Development Needs


The face of Web development is constantly changing. Hiring staff that can keep up with all of its changes becomes more and more challenging as technology evolves. And this is especially the case with Ruby on Rails (RoR) development. The popularity seen by the adoption of RoR has seen an extreme increase of interest by those wanting to become RoR developers. With the new surge of developers added to the programming pool, how does a client determine which candidate is truly qualified when it comes to joining a RoR development team?

Like many other programming technologies, it is best to Hire Ruby on Rails Developers who has deep knowledge of Ruby on Rails. While teams often do benefit from “generalists” who are suited to a wide variety of technologies, having a developer with specific RoR development experience will save considerable time. Veteran RoR developers will minimize the effort required by those lacking the requisite experience they already have. So it’s essential for a RoR developer’s team to consist of teammates equally competent in RoR development, with every colleague being already on the same page as the others.

Today’s modern Web development cannot afford any slowdowns during the development process, nor can today’s enterprises afford to accept mistakes and failures created by those unfamiliar with the RoR engineering process. The best possible output is derived from a RoR development team that consistently works together in a professional, uniform fashion.

This is not to say that developers only need to concern themselves with Web technology. The best are skilled in a number of skills and competencies that are geared towards a well-rounded, interdisciplinary approach to solving real-world problems that are found throughout the Web development process.

All Web development may seem to focus solely on Web pages and the technology upon which they are served, but in reality Web development is a human endeavor that transcends electronic media. Web development is a human endeavor designed to solve human problems.

Solid RoR Development teams realize this is more inclined to deliver clients effective, long-term solutions than those who simply develop for technology’s sake. This should also be the case for its individual members.

Choose Ruby On Rails For Simplicity In Programming


Ruby on Rails often simply referred to as Rails, also known as RoR Development, is a 100 % free web development system framework meant for faster web applications. The Ruby programming is a free program and is constantly improved by Ruby on Rails developers to make it more better and user friendly.

Ruby on Rails is based on the MVC (Model View Controller) architecture that enables the data to be separated from presentation. Rails framework has a large AJAX code which it uses to generate AJAX rule and the required Java script is automatically generated.

Ruby on Rails Developers follow the latest trends in Ruby on Rails programming such as Test Driven Development, Pair Programming and Quality programs to ensure the code quality is excellent for high volume scalability. So if you looking for 100 % free web style development, 100 % free applications, RoR solutions, RoR developers will help you to achieve your company goals.

Advantages of Using Ruby on Rails

1. Rails works well with various web servers and databases as it is really easy to set up web solutions using rails.

2. It’s Perfect for Web Technologies, The great thing about it is that you can get a working prototype up and running extremely quickly. Checking the feasibility of a project is made much easier because of this. In addition, cracks in the scope and direction of a web application can be fixed early on in the development cycle.

3. You can Saves Money, Whether you’re the project lead or the client, no one is going to complain about this one. To put it simply, RoR Development can cut significant chunks out of web project. The framework is 100% free and runs on Linux, which is also open-source. It’s also easy to work with from a developer’s perspective.

4. The beauty of Ruby on Rails is that you can create your own building blocks for plug-and-play functionality. Now, it’s on as simple as snapping your fingers, but it’s much easier to do it with Ruby on Rails than with any other technology on the market today.

5. Rails provides easy and easy development with high top quality results.

6. The Ruby on rails framework software also supports MySQL, SQL, SQL Server, DB2 and Oracle.
ROR CMS provides very flexible solutions,

7. Rails applications are personalized to quality for an individual or a company and best fit for all kind of web application. Rails architecture is used and most preferred for development of CMS, e-commerce, portals, collaboration, and community.

8. The Big Players Use It

You know that there’s something seriously right about Ruby on Rails when reading the list of companies that currently use it. Let’s have a look at just a small selection:

  • Hulu
  • Groupon
  • LivingSocial
  • Twitter
  • Basecamp
  • Realestate.com.au

Ruby on Rails is not only ideal for the larger companies, but it’s perfect for startups or local businesses as well. In a web landscape where you need to stand out to make something out of your project, Ruby on Rails allows your web application to break free from the standardization of template solutions at a cost that won’t cripple your bottom line.