Skip to content

Instantly share code, notes, and snippets.

@oddlyzen
Created February 10, 2009 16:42
Show Gist options
  • Save oddlyzen/61453 to your computer and use it in GitHub Desktop.
Save oddlyzen/61453 to your computer and use it in GitHub Desktop.
For code review by ZepFrog team (2/13/09)
# init.rb
ActiveRecord::Base.send(:include, ZepFrog::DasPermalinkor)
# /lib/zepfrog/das_permalinkor.rb
module ZepFrog
module DasPermalinkor
def self.included(base)
base.extend Permalinkor
end
module Permalinkor
def das_permalinked(options = {})
options[:name] ||= :permalink
options[:source] ||= :title
unless included_modules.include? InstanceMethods
class_inheritable_accessor :options
extend ClassMethods
include InstanceMethods
end
self.options = options
end
end
module ClassMethods
def permalinked_find(key, *params)
self.send("find_by_#{options[:name].to_s}".to_sym, key, *params)
end
end
module InstanceMethods
def to_param
if self.send(options[:name]).nil?
self.das_permalink = self.send(options[:source]).slugify
self.save!
end
self.send options[:name]
end
def das_permalink
self.send options[:name]
end
def das_permalink=(val)
self[options[:name]] = val
end
end
end
end
# test/das_permalinkor_test.rb
require 'test/unit'
class DasPermalinkorTest < Test::Unit::TestCase
def setup
return Mock.new(:permalink => '', :title => 'Zeppity Do Da Zeppity Yay')
end
def test_this_plugin
mock = Mock.new(:permalink => '', :title => 'Zeppity Do Da Zeppity Yay')
assert_not_equal nil, mock.to_param
assert_equal "Zeppity-Do-Da-Zeppity-Yay", mock.to_param
assert_equal "Zeppity-Do-Da-Zeppity-Yay", mock.das_permalink
mock.das_permalink = "Hello There World"
assert_equal "Hello-There-World", mock.das_permalink
end
end
class Mock
attr_accessor :permalink, :title
def id
1
end
def initialize(params = {})
self.permalink = params[:permalink] ||= nil
self.title = params[:title] ||= nil
end
def to_param
if self.permalink == ''
self.permalink = self.title.slugify
end
self.permalink
end
def das_permalink
self.permalink
end
def das_permalink=(val)
self.permalink = val.slugify
end
def self.permalinked_find(key, *params)
a = []
[1...10].each do |m|
a << m = Mock.new(:permalink => '', :title => 'Zeppity Do Da Zeppity Yay')
end
end
end
class String
def slugify
self.gsub(/\'/, '').gsub(/[^a-z0-9]+/i, '-')
end
def slugify!
self.gsub!(/\'/, '').gsub(/[^a-z0-9]+/i, '-')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment