Custom model callbacks in RubyOnRails

RubyOnRails provides us with many model callbacks around the object’s lifecycle when object is being created, updated or destroyed. For example: before_create, after_create, before_update, after_destroy etc. We use them to write & run our code around the object’s lifecycle by defining a method and associating them as one of the callbacks.

But then how can we make a piece of code execute as a callback for any another defined method except create, update, save and destroy? For example, let’s say we have a model Article and we want to execute something just before and after an article is being published without hooking into model’s before_save and after_save callbacks?

RubyOnRails or more precisely ActiveRecord provides us with a module ActiveModel::Callbacks, which allows us to define and register custom callbacks using define_model_callbacks method. Lets have a look at the snippet below for the above scenario:


class Article 
  extend ActiveModel::Callbacks
  
  define_model_callbacks :publish, :only => [:before, :after]

  before_publish :check_publishability
  after_publish  :notify_subscribers

  def publish
    run_callbacks :publish do
      puts "Publishing article..."
    end
  end

  private
  
  def check_publishability
    puts "Checking publishability rules..."
  end

  def notify_subscribers
    puts "Notifying subscribers..."
  end

end

By default define_model_callbacks provides with all three callbacks i.e. before, after and around, but here in our example we have chosen to have just before and after callbacks by specifying a hash :only => [:after, :before] since only those two were needed. By using define_model_callbacks :publish, :only => [:after, :before] we got two new callback before_publish and after_publish, which we then used to register our callback methods.

So now when we will call publish method on an article object, check_publishability will be executed as a before callback and notify_subscribers will be executed as an after callback for the publish method.

One point to note here is that the code in the publish method should be wrapped in run_callback :publish block, so that when it is called on an object, its callbacks are executed too.

For the snippet above run_callback triggers before callbacks, yield the block given and then trigger after callbacks.

More information on define_model_callbacks can be found here.


>> article = Article.last
>> article.publish
Checking publishability rules...
Publishing article...
Notifying subscribers...

 

Reasons to consider Spree when choosing an e-commerce platform

Don’t select your next e-commerce platform without reading about these 13 factors first.

Online business has become a dominant and growing force. Global sales through e-commerce topped $1 trillion in 2012, with North American and Asia-Pacific nations accounting for nearly 70% of it. Projections are that global e-commerce sales will reach $1.5 trillion in 2016.

“Conduct better due diligence of the platform”

Over 60% of medium to large e-commerce site owners claim they should have done better due diligence on the platform they selected for their store. Much too often do businesses face constrained growth or incur significant losses due to misguided platform selections.

ecommerce-development

If you are ready to sell online, choosing the best e-commerce system for your business can be a challenging and confusing process. Based on our deep expertise of rails e-commerce and Spree development, this blog will help make sense of 13 factors you should be considering for selecting an e-commerce platform for your store and how spree stacks up against the competition on those factors.

1. License
There is no “enterprise” edition of Spree – its all the same software. Enterprise clients, small and medium sized businesses can use Open Source Spree for commercial purpose without paying any license fee.

2. Standards
Your store must run on a standards-based platform that can be supported by standard skill sets in the wider marketplace. Spree is built on top of the popular Ruby on Rails framework that enables quicker launch, easier changes and brings cost-effectiveness to the entire project.

3. Design
Easily modify your store design. Spree makes it easier to customize the view layer and also to write an extension that modifies the existing views. It is also simple to take an existing theme and make minor tweaks to it.

4. Your store should adapt
Common, expected features need a complex set of capabilities required to keep best-in-class Web stores appealing, responsive, and performing well at high transaction volumes over the long term.

5. Mobile
Your customers are using mobile devices. Providing mobile support is not an optional feature. Spree stores renders well on mobile phones out of box and can be further customized to the business requirements.

View Vinsol’s Successful Projects

6. Extensibility
It is normal for store owners to want additional or differentiated features . Many of those features are available as third party Spree extensions as well as can be developed quickly using its robust API. The extensions are open source and can be modified if needed since the source code is available.

7. Marketplace
Can you extend your e-commerce platform to enable other vendors to create online shops on your platform? We used Spree to create a marketplace for a client to add more revenue streams.

8. Integration
As online stores have become more imaginative about how they mix their Web and mobile channel with other customer and internal touch points, clean and easy integration is mandatory for any modern e-commerce system.

9. Business User Control
Look for platforms that your business managers can use themselves. Can product and category managers control their parts of the catalog? We built custom permissions in Spree so business users can use the system without getting overwhelmed.

For your e-commerce platform contact Vinsol here

10. Product catalog
The product catalog is the online repository for every item you sell. It can be difficult to predict what kind of products you will be selling in the future, and what other applications may may need to populate your catalogs. Sprees’s product catalog data design comprising of products, variants, properties and taxonomy allows store owners to define and carry a wide products with very different types of attributes.

11. Customer behaviour
Try to find a solution that can monitor customer activity on your site, and can then take action based on identified behavior to improve your sales. Spree doesn’t come with out of box customer analytics but can be integrated with third party recommendation engines.

12. Search Capability
Searching for products is a key operation for commerce sites, where we need both speed and flexibility. Spree supports this by providing an API that allows plug-in and configuration of a variety of specialized, high-performance search platforms.

13. ScalabilitY Factors
YES, SPREE CAN SCALE. An e-commerce Website is only as good as its ability to handle its peak traffic. As your online store’s popularity increases, it needs to scale with minimal effort so you can avoid incurring proportionate development and hardware management costs.

Download Solution Guide

Updated At: 04.07.2014