Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

view_models

Package Overview
Dependencies
Maintainers
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

view_models

  • 4.0.1
  • Rubygems
  • Socket score

Version published
Maintainers
4
Created
Source

h1. View Models !https://secure.travis-ci.org/beatrichartz/view_models.png(Build Status)!:http://travis-ci.org/beatrichartz/view_models "!https://codeclimate.com/github/beatrichartz/view_models.png!":https://codeclimate.com/github/beatrichartz/view_models

A representer solution for Rails 3 and 4 inspired by Florian Hankes View Models for Rails 2 (http://florianhanke.com/view_models). For older versions of Rails please use versions up to 3. You may find view models useful (or not). Fact: They will keep code out of your views. Because view models do not like code in your view.

h2. Installing View Models

Add this to your gemfile

gem "view_models",   "~> 4.0"

And this to your application.rb: (It adds the app folder to the autoload paths, which is necessary for the view models to load)

config.autoload_paths += %W(#{config.root}/app)

Create a directory "view_models" in your app folder, and you're good to go.

mkdir ./app/view_models

h2. TODOs

What you can look forward to in future versions of this gem:

  • Bootstrapping for easier installation

h2. Basic Usage

Let's say you have a model User (with a first and a last name and an address in the database):

class User < ActiveRecord::Base
  
  has_many :posts
  
end

Write a corresponding view model user.rb in your view_models folder

class ViewModels::User < ViewModels::Base
  
  # model readers make model methods accessible on the view model object
  #
  model_reader :first_name, :last_name, :street, :street_number, :zip_code, :city
  
  # Write helper methods which benefit from model readers
  #
  def name
    [first_name, last_name].join ' '
  end
  
  # Access the model by using «model»
  #
  def creation_time
    time_ago_in_words model.created_at
  end
  
end

In your view, call the view_model for a model by using «view_model_for»

- view_model = view_model_for(@user)
%h2= view_model.name
%h2= view_model.creation_time

All beautiful, you may think, but...

h2. Why View Models? (aka «The Problem»)

Ever felt like putting something like this in your views (example in haml)?

#user
  .name= [@user.first_name, @user.last_name].join ' '
  .address= [@user.street, @user.street_number, @user.zip_code, @user.city].join ' '

Well, that may feel good if you're in a hurry. Soon there comes the time when you use this code in more than one place. Time to build a helper:

module UserHelper
  def user_name user
    [user.first_name, user.last_name].join ' '
  end

  def user_address user
    [user.street, user.street_number, user.zip_code, user.city].join ' '
  end
end

#user
  .name= user_name @user
  .address= user_address @user

It may be a lot cleaner, but something just does not feel right. Right, but what? Well, for instance, you have to namespace all your methods with «user» so your methods don't get messy. Second, you have to include the helper either in every context you use it, or even in the whole app. If only you had a polymorphic object to represent your models in the views...

h3. Meet View Models (aka «The Solution»)

View models are pretty, because they represent your models in your views. They look good in every context, and therefore make you look good, too. Take our example from before:

class ViewModels::User < ViewModels::Base

  model_reader :first_name, :last_name, :street, :street_number, :zip_code, :city
  
  def name
    [first_name, last_name].join ' '
  end

  def address
    [street, street_number, zip_code, city].join ' '
  end
  
end

And your view will look like this:

- user_view_model = view_model_for(@user)
#user
  .name= user_view_model.name
  .address= user_view_model.address

No helper inclusion needed, no further noise involved. In fact, you can make it even prettier: What if you needed that partial with the user name and address somewhere else in your code?

h3. Meet View Models render_as method

View models feature template rendering: You can render any partial in your views, following your views directory tree structure: A view_model variable will automatically be included as a local variable in your partial if you render it with view models:

Let's say you have the user model from before, and the following partial written for the view model to render named "info":

#user
  .name= view_model.name
  .address= view_model.address

Now everything you have to do to render that partial is:

= view_model_for(@user).render_as :info

View models feature hierarchical template rendering. That means, if you have a parent view model which has an identical partial already installed, you do not need to copy identical code just to render the same template. The view model will lookup its inheritance chain and Rails template paths to find the suitable partial. Which brings us to another great feature:

h3. View Models can haz inheritance

Ever tried to do inheritance in Rails helpers? Right. View Models, on the other side, love inheritance. They do not need arguments to display a formatted creation time for all your models. Consider the following:

h4. The View Model Way

You can generate a view model tree structure with a view model for your whole app for your other view models to inherit from. The polymorphic class matching of the view models ignores the missing class YourApp candidly.

class ViewModels::YourApp < ViewModels::Base

  def creation_time
    time_ago_in_words model.created_at
  end

end

class ViewModels::User < ViewModels::YourApp
end

In your view:

= view_model_for(@user).creation_time

h4. The Helper Way

Imagine how to do this in a helper ? Well, better go ahead and use time_ago_in_words everywhere.

h2. Testing View Models

Testing View Models is easy. You can use the view models initializer instead of the view_model_for mapping (example in rspec with factory girl):

describe "ViewModels::User" do
  let(:user) { build_stubbed(:user) }
  subject { ViewModels::User.new(user, @controller) } # @controller may be nil or the controller
  
  describe "model_readers"
    .. there you go
  end
end

h2. Further reads

"Rubygems":http://rubygems.org/gems/view_models "Bug Tracker":http://github.com/beatrichartz/view_models/issues "Source [Github]":http://github.com/beatrichartz/view_models

FAQs

Package last updated on 04 Jan 2014

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc