in Programming, Railscasts, Uncategorized

Stringify Time Gem

This gem was created following the Rails plugin made in Railscast 033 Making a Plugin.

Installation

Add this line to your application’s Gemfile:

gem 'stringify_time'                                                   

And then execute:

$ bundle                                                               

Or install it yourself as:

$ gem install stringify_time                                           

Usage

Within an the model add stringify_time passing in a symbol that you want to set as the attribute you want aliased as a virtual attribute string.

class Task < ActiveRecord::Base
    stringify_time :due_at
end

This will create the due_at_string getter and setter methods within the Task model. You can then access this attribute in the views like so:

_form.html.erb

<%= form_for @task do |f| %>
  ...
  <div class="field">
    <%= f.label :due_at %><br>
    <%= f.text_field :due_at_string %>
  </div>
  ...
<% end %>

Your users are now able to type in the date into a text field instead of using the Rails’ default datetime_select dropdowns.

Write a Comment

Comment