Skip to content

Instantly share code, notes, and snippets.

@joemerante
Created July 22, 2014 17:54
Show Gist options
  • Save joemerante/ab83d7bde85a682b9608 to your computer and use it in GitHub Desktop.
Save joemerante/ab83d7bde85a682b9608 to your computer and use it in GitHub Desktop.
Example of a simple use of eval()
# Goes with http://joemerante.blogspot.com/2014/07/may-tmil-touch-of-eval.html
# app/models/subscription.rb
class Subscription < ActiveRecord::Base
belongs_to :plan
after_create :set_expiration
# ...
def expired?
self.expiration < DateTime.now
end
# ....
private
def set_expiration
# plan.duration is stored as "2.weeks", "3.months" etc
self.expiration = DateTime.now + eval(plan.duration)
save!
end
end
# spec/models/subscription_spec.rb
require 'spec_helper'
describe Subscription do
it "sets an expiration in a callback" do
Timecop.freeze(DateTime.now) do
user = FactoryGirl.create(:user)
plan = FactoryGirl.create(:plan) # duration on factory is "3.months"
subscription = FactoryGirl.create(:subscription, user_id: user.id, plan_id: plan.id)
expect(subscription.expiration).to eq(DateTime.now + 3.months)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment