Zachary Palmer

Zachary Palmer

1563433754

What's New in Rails 6?

As most Ruby on Rails fans might be aware, Rails 6 was released this April at RailsConf 2019 and brought a number of eagerly awaited features and changes. Here is a quick recap of the key Rails 6 features you are likely to be using moving forward

For starters, remember that Rails 6 requires Ruby 2.5+ and upgraded databases. So, make sure you have a plan to upgrade your systems accordingly, in case you have not done so already.

Testing in Rails 6

As professional Ruby on Rails developers, we aim to ensure maximum coverage for our code. However, testing becomes a tedious activity when our test cases become “heavy” and we have to wait several minutes, or even hours, just to get the test cases executed.

Parallel Testing

Well, Rails 6 has an answer here. It has added a parallelize method to the ActiveSupport::TestCase which allows you to parallelize the test suite with forked processes.

So, what you need to do to parallelize the processes for your tests is add this to your test_helper.rb:

parallelize(workers: 2)

Alternatively, we can replace our previously used commands for running tests. For example, bin/rails test OR bin/rspec spec can now be replaced by PARALLEL_WORKERS=15 rails test OR PARALLEL_WORKERS=15 rspec spec.

Accordingly, you can change the commands for running the test suites on different CI platforms like Travis, Gitlab, CircleCI, and others.

There are also hooks when each process is created/destroyed, which can be used as follows:

class ActiveSupport::TestCase
  parallelize_setup do |worker|
    # setup databases
  end
  parallelize_teardown do |worker|
    # cleanup databases
  end
  parallelize(workers: :number_of_processors)
end

Note: If you’d like to learn more, you can check out Rails Guides for additional details.

Action Cable Testing

Since we were talking about efficient testing, let’s also understand how Action Cable, one of the most salient features of Rails 5, has improved. Now it is possible to test Action Cable at any level: connections, channels, and broadcasts.

Connection tests aim to check whether a connection’s identifiers get assigned properly or that any improper connection requests are rejected:

class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase
  test "connects with params" do
 
    connect params: { user_id: 42 }
    OR
    cookies.signed[:user_id] = "42"
    connect
 
    assert_equal connection.user_id, "42"
  end
  test "rejects connection without params" do
    assert_reject_connection { connect }
  end
end

Channel tests can be written to check whether users can subscribe to channels and the channel has a stream:

class ChatChannelTest < ActionCable::Channel::TestCase
  test "subscribes and stream for room" do
    # Simulate a subscription creation by calling `subscribe`
    subscribe room: "15"
    # You can access the Channel object via `subscription` in tests
    assert subscription.confirmed?
    assert_has_stream "chat_15"
  end
end

Broadcasting to channels can be tested like this:

# app/jobs/chat_relay_job.rb
class ChatRelayJob < ApplicationJob
  def perform_later(room, message)
    ChatChannel.broadcast_to room, text: message
  end
end
# test/jobs/chat_relay_job_test.rb
require 'test_helper'
class ChatRelayJobTest < ActiveJob::TestCase
  include ActionCable::TestHelper
  test "broadcast message to room" do
    room = rooms(:all)
    assert_broadcast_on(ChatChannel.broadcasting_for(room), text: "Hi!") do
     ChatRelayJob.perform_now(room, "Hi!")
    end
  end
end

Bulk Insert and Upsert

At some point, we all need to insert multiple records in one go and have found many workarounds when doing so. Well, Rails 6 comes with a new method out of the box—insert_all, similar to update_all.

It won’t fire any callbacks and will execute a single SQL query. There is an additional method upsert_all which allows you to use the upsert operation which is exposed by many modern databases like Postgres. So now you can reduce your insert queries and make your code more optimized. Also, say goodbye to previously used gems like activerecord-import.

A single INSERT SQL query is prepared by these methods, and a single SQL statement is sent to the database, without instantiating the model, or invoking Active Record callbacks and validations. It is also possible to define criteria when a primary key—unique indexes or unique constraints are violated with an option to either skip or run upsert queries.

Some examples are below:

result = Article.insert_all(
  [
    { id: 1,
      title: 'Handling 1M Requests Per Second',
      author: 'John',
      slug: '1m-req-per-second' },
    #...snip...
  ],
  returning: %w[ id title ],
  unique_by: :index_articles_on_title_and_author
)
 
 
result = Article.upsert_all(
  [
    { id: 1, title: 'Handling 1M Requests Per Second', author: 'John', slug: '1m-req-per-second' },
    { id: 1, .... }, # duplicate 'id' here
    { id: 2, .... },
    { id: 3, .... }, # duplicate 'title' and 'author' here
    { id: 4, .... },
    { id: 5, .... }, # duplicate 'slug' here
    { id: 6, .... }
  ]
)

The methods insert, insert! and upsert are wrappers around insert_all, insert_all! and upsert_all, respectively.

Switching Between Multiple Databases

One of the main features many big applications will appreciate is this one: Rails 6 has finally added support for multiple databases for your application, built in and ready to go, out of the box!

Of course, the design choice is still yours, whether you want to break your application into multiple microservices with each having a separate database, or take a monolithic route, or add several read replicas for your application.

However, having the ability to do it in such an easy manner has the potential to save a lot of time on the development front.

So, this is how your new database.yml file will look:

development:
  primary:
    database: my_primary_db
    user: root
  primary_replica:
    database: my_primary_db
    user: ro_user
    replica: true
  animals:
    database: my_animals_db
    user: root
  animals_replica
    database: my_animals_db
    user: ro_user
    replica: true

Here are interesting ways of specifying how to switch to different databases:

class AnimalsModel < ApplicationRecord
  self.abstract_class = true
 
  connects_to database: { writing: :animals_primary, reading: :animals_replica }
end
 
class Dog < AnimalsModel
  # connected to both the animals_primary db for writing and the animals_replica for reading
end

Here is the official GitHub page, which is nicely documented as well. Personally, I am looking forward to having database sharding capabilities in future Rails updates as well.

Action Mailbox

Another interesting React 6 feature is the addition of Action Mailbox, which adds the capability to route incoming emails to the controller like mailboxes for processing in Rails.

Action Mailbox features ingresses for Mailgun, Mandrill, Postmark, and SendGrid. You can also handle inbound emails directly via built-in Exim, Postfix, and Qmail ingresses. Now, you can probably imagine the potential benefits without going into more detail. It may be directly processing mails from a help desk to automating support tickets—Rails 6 allows customers to reply directly through email, and much, much more. The floor is open for you to explore this feature and come up with an approach that is ideal for your application.

Here is a small example to understand how to use Action Mailbox:

COMMENTS_REGEX = /^comment\+(.+)@example\.com/i
 
# app/mailboxes/application_mailbox.rb
class ApplicationMailbox < ActionMailbox::Base
  routing COMMENTS_REGEX => :comments
end
 
# app/mailboxes/comments_mailbox.rb
class CommentsMailbox < ApplicationMailbox
  def process
    user = User.find_by(email: mail.from)
    post_uuid = COMMENTS_REGEX.match(mail.to)[1]
   
    post = Post.find_by(uuid: post_uuid)
    post.comments.create(user: user, content: mail.body)
  end
end

Also, the new way of configuring emails is as follows (taking the example of Sendgrid):

# config/environments/production.rb
config.action_mailbox.ingress = :sendgrid

Use rails credentials:edit to add the password to your application’s encrypted credentials under action_mailbox.ingress_password, where Action Mailbox will automatically find it:

action_mailbox:
  ingress_password: …

Configure the SendGrid Inbound Parse to forward inbound emails to /rails/action_mailbox/sendgrid/inbound_emails with the username actionmailbox and the password you previously generated. If your application lives at <a href="https://example.com" target="_blank">https://example.com</a>, you would configure SendGrid with the following URL:

https://actionmailbox:PASSWORD@example.com/rails/action_mailbox/sendgrid/i 

Zeitwerk

Zeitwerk is the new code loader for Ruby. Given a conventional file structure, Zeitwerk loads your project’s classes and modules on demand, meaning you don’t need to write require calls for your own files. To enable it in Rails 6, you can do the following:

config.autoloader = :zeitwerk

You can read more about Zeitwerk here.

Optimizer Hints

You are concerned that some of your queries are taking too long to execute? Well, now you have a way to define time-outs for your queries, too.

The following statement will raise an StatementTimeout exception if the query takes longer than normal to execute:

User.optimizer_hints("MAX_EXECUTION_TIME(5000)").all

It is supported by MySQL and you’ll have to explore if your database supports it.

Truncate Database

What about seeding data? The following statement will truncate all your database tables and you can then proceed to seeding your data:

rails db:truncate_all

No more deleting your databases to seed. You will probably agree this is an elegant and quick solution.

Action Text

Perhaps another notable feature for many applications that play with WYSIWYG editors is the addition of support for Trix editor natively into Rails 6 applications. This will certainly be a good upgrade/addition for many projects.

Most WYSIWYG HTML editors are enormous in scope—each browser’s implementation has its own set of bugs and quirks, and JavaScript developers are left to resolve the inconsistencies. Trix sidesteps these inconsistencies by treating contenteditable as an I/O device: When input makes its way to the editor, Trix converts that input into an editing operation on its internal document model, then re-renders that document back into the editor. This gives Trix complete control over what happens after every keystroke.

Installation:

rails action_text:install
 
# app/models/message.rb
class Message < ApplicationRecord
  has_rich_text :content
end

You can explore Action Text in further detail in the official documentation, here.

Security

No serious upgrade is complete without a few security enhancements. Rails 6 doesn’t disappoint on the security front, either. The first notable security upgrade is the addition of support for Host Authorization.

Host Authorization is a new middleware that guards against DNS rebinding attacks by explicitly permitting the hosts a request can be sent to. What this means is that you can define the hosts that can access your applications.

Another security upgrade is meant to thwart attacks that attempt to copy the signed/encrypted value of a cookie and use it as the value of another cookie. It does so by stashing the cookie name in the purpose field which is then signed/encrypted along with the cookie value. Then, on the server-side read, we verify the cookie names and discard any attacked cookies. Enable action_dispatch.use_cookies_with_metadata to use this feature, which writes cookies with the new purpose and expiry metadata embedded.

Webpack as the Default Bundler

As is the de facto standard with many modern JavaScript frameworks for front-end development, Rails 6 has added Webpack as the default JavaScript bundler through webpacker gem, replacing the Rails Asset pipeline. This is a relatively straightforward addition, and we won’t go into much detail. Suffice to say that Webpack will bring some relief to overworked front-end developers.

Preventing Race Conditions

Rails 6 has a new method which is used to prevent SELECT/INSERT race conditions in our code (I am sure many readers have had the misfortune of encountering race conditions as they scale their project). Here is the GitHub thread in case you need additional info.

The underlying table must have the relevant columns defined with unique constraints. While we avoid the race condition between SELECT → INSERT from #find_or_create_by, we actually have another race condition between INSERT → SELECT, which can be triggered if a DELETE between those two statements is run by another client. But, for most applications, that’s a condition we’re significantly less likely to hit.

Credentials in Rails 6

Since the days of Rails 5.2, credentials have been named a new “Rails way” to deal with sensitive information with a promise to get rid of infamous .env files once and for all. With credentials, encrypted keys for third-party services can be checked directly into the source control.

Until now, however, Rails used the same encrypted file for all environments, which made dealing with different keys in development and production a little tricky, especially when dealing with big projects and legacy code.

In Rails 6, this is finally solved with support for per-environment credentials. Again, further details can be explored on the official GitHub thread.

#ruby-on-rails #ruby #web-development

What is GEEK

Buddha Community

What's New in Rails 6?

Ruby on Rails Development Services | Ruby on Rails Development

Ruby on Rails is a development tool that offers Web & Mobile App Developers a structure for all the codes they write resulting in time-saving with all the common repetitive tasks during the development stage.

Want to build a Website or Mobile App with Ruby on Rails Framework

Connect with WebClues Infotech, the top Web & Mobile App development company that has served more than 600 clients worldwide. After serving them with our services WebClues Infotech is ready to serve you in fulfilling your Web & Mobile App Development Requirements.

Want to know more about development on the Ruby on Rails framework?

Visit: https://www.webcluesinfotech.com/ruby-on-rails-development/

Share your requirements https://www.webcluesinfotech.com/contact-us/

View Portfolio https://www.webcluesinfotech.com/portfolio/

#ruby on rails development services #ruby on rails development #ruby on rails web development company #ruby on rails development company #hire ruby on rails developer #hire ruby on rails developers

Marcelle  Smith

Marcelle Smith

1598839653

Authenticating Your API Using "Knock Gem" in Rails

Due to the inability to generate a well-defined way to authenticate rails API, I have sourced out this information in order to help me and you have a way of authenticating our rails API token. This tutorial would be based on the latest version (6.0) of Ruby on Rails.

In getting this set up as well as up and doing, the few steps through which the processes would be implemented are listed below:

Step 1:

We would need to, first of all, generate a new rails app as we embark on the journey. Follow the example given below:

$ rails new sample-app --api -d=postgresql -T
$ cd sample-app
$ rails db:create
$ rails db:migrate

Step 2:

In order to gain access to the API, we would need to uncomment or remove Cors gems as that serves as permission into gaining access to the API

gem “rack-cors”

After uncommented the gem ‘rack-cors’ then we run this command below

$ bundle install

#ruby-on-rails #rails #rails-api #knock-gem #ruby #software-development #rails-only-api

Emily Johnson

1599568900

Hire Ruby on Rails Developer | Hire RoR Developer

Are you looking for Ruby on Rails developers for building next-generation web applications?

Bacancy Technology is top-notch Ruby on Rails development company providing world’s best Ruby On Rails Development Services With 8+ Years Of Experience. Hire Ruby on Rails developer for web application that reflects cutting-edge solutions for your business needs. Access 40+ RoR developers. save upto 40% on development cost.

Get top Ruby on Rails developers from Bacancy Technology, contact now and hire your choice of developer’s within 48 Hours, to know more about our RoR services & pricing: https://www.bacancytechnology.com/ruby-on-rails-development

ruby on rails development

#hire ruby on rails developer #ruby on rails developer #ruby on rails development company #ruby on rails development services #hire ror developer #ruby on rails development

Shardul Bhatt

Shardul Bhatt

1618576835

Why should we use Ruby on Rails for Software Development?

What is Rails, Ruby on Rails?

Rails is a server-side web application development framework written in the Ruby programming language. Its emergence in 2005 has influenced and impacted web application development to a vast range, including but not limited to seamless database tables, migrations, and scaffolding of views. In the simplest understanding, Rails is a highly productive and intuitive software developer. 

Websites and applications of any complexity can be achieved with Ruby on Rails. The software is designed to perceive the needs of ruby on rails developers and encourage them with the best way out. It is designed to allow developers to write lesser code while spiking productivity much more than any other framework or language. Ruby on Rails rapid application development offers everyday web development tasks easier and uniquely out-of-the-box, both with the same effectiveness.

The Ruby on Rails framework is based on two philosophies:

 

  • Don’t Repeat Yourself (DRY): It is a software development principle that ensures that every piece or entity of knowledge must be assigned with a single and unambiguous representation within a development system.

    It not only reduces the need to write lengthy codes but also eliminates the repetitive writing of codes. As a result, it provides a much more manageable web app development with the least possible bugs.

 

  • Convention over Configuration (CoC): It indicates the highly opinionated feature that the Ruby on Rails framework possesses. It offers ready-made solutions or the “best way out” for many tasks in a web application and defaults them to the convention without the need for external specification. The programmer using the software is required to specify only the unconventional aspects of the web application. 

Some of the commonly known websites built by the Ruby on Rails software developers are Instacart, Scribd, Shopify, Github, ConvertKit, Soundcloud, GoodReads, Airbnb. It finds its application in Sa-as Solutions, Social Networking Platforms, Dating websites, Stock Exchange Platforms, etc.  

Read more: Why Ruby on Rails is Perfect for eCommerce Web Development

Why use Ruby on Rails: The multifold benefits

  • Community and its abundant resources 

    • There is a large community that is dedicated to Ruby on Rails that keeps it up-to-date and indeed encourages its family of developers to continue using it. They make sure the benefits are soaring with every update they make. 

    • The community is committed to developing several ready-to-use code packages, commonly known as gems, for its users. They discuss and announce new project launches, help each other with queries, and engage in framework discussions and betterment. While Ruby on Rails helps developers in rapid application development, it also connects and grows businesses together.

  • Project Scalability

    • To talk about scalability, we indicate the ability to grow and manage more and more user requests per minute (RPM). However, this depends on the architecture rather than the framework. The right architecture of Ruby on Rails web application development allows it to write bulky codes and programs as compared to early-stage difficulties with scalability. 

    • It uses the Representational State Transfer (REST) architecture. This will enable Rails to create efficient web applications based on Rails 6, launched last year in 2020, which addresses most scalability issues. The portable components are agile and help in a better understanding of new requirements and needful adaptations for any business. The framework and architecture allow both vertical and horizontal scalability.

  • Fast Application Development and Cost Effectiveness

    • Ruby on Rails is lucid, logical, and has lean code requirements, thereby cutting down redundancy and improving the overall development speed. Lesser amount of code is proportional to lesser time investment with optimal results. The more time it takes for development, the more expensive it becomes for the end customers.

    • Considering the ready-made code modules/packages (gems) available, Ruby on Rails development company will less time and money are spent creating and modifying Rails websites and applications. Another advantage that has made Ruby on Rails super attractive for startups is its use of Model-View-Controller (MVC) architecture. It has a component separation scheme that speeds up the web development process and fixes any errors that occur.  

  • Data Protection

    • Rails framework and the Ruby on Rails community put in a lot of efforts for data protection and security of its customer base. It is also one of the efficient frameworks for developing database-backed applications. 

    • The developers at Ruby on Rails cover many aspects of cybersecurity, including encryptions of  passwords, credit card information, and users’ personal database. Special measures are taken to prevent the framework from SQL injections and XSS attacks. 

  • Ruby on Rails Enterprise Application Development

    • Ruby on Rails simplifies the daily operations and lowers the cost of enterprise app developments. The prominent features include data management, seamless updating of applications, easy and efficient code development, and high scalability, as discussed above. 

    • Ruby on Rails enterprise application development is preferred by companies and is slightly cost-intensive. It can be easily integrated with third-party apps like Oracle Business, Oracle, Windows services, and others. Ruby enterprise app development allows the developers and programmers to solve the problems at the root level, given its transparency.

Ruby on Rails V/S Django

Checkout Blog on Django vs Ruby on Rails Comparison

Bottom Line

There are several reasons to prefer Ruby on Rails discussed above and extend further to early detection of errors, reduced time to market, and easy adaptation for API developments. It makes web programming much easier and simplifies website building of any complexity. Its flexibility and acceptance among new developers and programmers make it the perfect, one-stop choice for software application development company in 2021. 

Source: https://techsite.io/p/2121044

#ruby on rails examples #ruby on rails rapid application development #ruby on rails web application development #ruby on rails software developer #ruby on rails enterprise application development

Stephie John

1606290330

What is ASO for Android & iOS Mobile App?

App Store Optimization is all about improving the visibility of a particular Android /iOS Mobile App on the App Store. Mobile App to optimize? Then go for Best SEO Company in New Zealand

How does ASO Really Work?
ASO is the process of improving the visibility of a mobile app in an app store. Just like search engine optimization (SEO) is for websites, App Store Optimization (ASO) is for mobile apps. Specifically, app store optimization includes the process of ranking highly in an app store’s search results and top charts rankings. Lia Infraservices the Top SEO Company in New Zealand and ASO marketers agrees that ranking higher in search results and top charts rankings will drive more downloads for an app.

ASO Focus on 2 Areas:
A. Search Optimization
B. Behavioral Approach

  1. Search Optimization:
    This part of App Store Optimization focuses on adjusting the name of the app and its keywords. When it comes to SEO services in New Zealand, each app is described by keywords, packed into a 100 character string. These keywords affect search rankings. The better the keywords, the higher the possibility for the app to appear in App Store search results.

/The more often the app appears in search results = the more installs /

Note: The app name is the strongest key phrase.

5 point method to Choose Keywords:
1.Create a list of general keywords based on the app description.
2.Find the Top 5 apps that target the already selected keywords.
3.Find keywords that work best for each of the 5 apps.
4.Now you should have created quite a large list of keywords. Get rid of those which don’t fit your app.
5.Create 100 characters, a comma separated string that contains the best keywords you chose.

  1. Behavioural Approach:
    App Store Optimization is not only about adjusting towards search algorithms, it’s also about human behavior. There are several areas on the Android/iOS Mobile App Store that trigger human decisions to make an install or to abandon it. These are the most important for us:

a.Application name
b.Rating
c.Screenshots / video preview
d.App description

Is your Mobile App Optimized?
When it comes to app downloads and revenue, approach the SEO Company in New Zealand, your app will do much better almost immediately after optimization. If you are interested in learning what the other factors that influence building an organic increase of app popularity are, you should get your mobile app developed by the expert SEO agency in New Zealand. Build your Android & iOS app at Lia Infraservices at cost and time effective.

#seo company in new zealand #seo services in new zealand #seo agency in new zealand #top seo company in new zealand #best seo company in new zealand #top digital marketing company in new zealand