From 2a4fa31aef507a62abe8a320a041a5ae3d430025 Mon Sep 17 00:00:00 2001 From: Dan Barber Date: Mon, 15 Apr 2013 12:35:08 +0100 Subject: [PATCH] Merge options. --- lib/slugtastic/model_additions.rb | 3 +- spec/slugtastic/model_additions_spec.rb | 37 +++++++++++++++++-------- 2 files changed, 28 insertions(+), 12 deletions(-) diff --git a/lib/slugtastic/model_additions.rb b/lib/slugtastic/model_additions.rb index 788cd95..b72e7d0 100644 --- a/lib/slugtastic/model_additions.rb +++ b/lib/slugtastic/model_additions.rb @@ -9,7 +9,8 @@ module Slugtastic # class Article < ActiveRecord::Base # has_slug :slug, :from => :title # end - def has_slug name, options = { :from => :title } + def has_slug name, options = {} + options.reverse_merge!({ :from => :title }) before_validation do |record| send("#{name}=", Slugtastic.generate_slug(send(options[:from]), options[:delimiter])) if send(name).nil? or send(name).blank? end diff --git a/spec/slugtastic/model_additions_spec.rb b/spec/slugtastic/model_additions_spec.rb index 88c6e28..be41858 100644 --- a/spec/slugtastic/model_additions_spec.rb +++ b/spec/slugtastic/model_additions_spec.rb @@ -1,30 +1,45 @@ # encoding: utf-8 require 'spec_helper' -class Model < SuperModel::Base +class BaseModel < SuperModel::Base include ActiveModel::Validations::Callbacks extend Slugtastic::ModelAdditions - attr_accessor :slug, :slug_2, :title - has_slug :slug, from: :title - has_slug :slug_2, from: :title, delimiter: "_" +end + +class Model < BaseModel + attr_accessor :slug, :name + has_slug :slug, from: :name +end + +class ModelDefault < BaseModel + attr_accessor :slug, :title + has_slug :slug +end + +class ModelDelimiter < BaseModel + attr_accessor :slug, :title + has_slug :slug, delimiter: "_" end describe Slugtastic::ModelAdditions do - it "generates a slug from the title" do - Model.create!(:title => "A Simple Title").slug.should eq "a-simple-title" + it "generates a slug from the name" do + Model.create!(:name => "A Simple Name").slug.should eq "a-simple-name" + end + + it "defaults to generating the slug from title" do + ModelDefault.create!(:title => "A Simple Title").slug.should eq "a-simple-title" end it "generates a slug from the title with delimiter substitutions" do - Model.create!(:title => "A Simple Title").slug_2.should eq "a_simple_title" + ModelDelimiter.create!(:title => "A Simple Title").slug.should eq "a_simple_title" end it "doesn't regenerate the slug if it already exists" do - model = Model.create!(:title => "A Simple Title") - model.slug.should eq "a-simple-title" + model = Model.create!(:name => "A Simple Name") + model.slug.should eq "a-simple-name" model.title = "A new title" model.save - model.slug.should eq "a-simple-title" - model.slug_2.should eq "a_simple_title" + model.slug.should eq "a-simple-name" end end