Skip to content

Commit

Permalink
Fix and some refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
gsmetal committed Mar 24, 2016
1 parent 75b4d84 commit f98aa88
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 32 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,20 @@ class Project < ActiveRecord::Base
end
```

You can use special methods in migrations:
```ruby
class CreateProjects < ActiveRecord::Migration
def change
create_table :projects do |t|
t.uuid
#...
end
# Or
add_uuid_column :projects
end
end
```

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
Expand Down
35 changes: 4 additions & 31 deletions lib/uuidable.rb
Original file line number Diff line number Diff line change
@@ -1,41 +1,14 @@
require 'uuidable/version'
require 'uuidable/migration'

require 'active_support'

# Main module
module Uuidable
extend ActiveSupport::Concern

class UuidChangeError < Exception; end

# ClassMethods
module ClassMethods
def uuidable
after_initialize { self.uuid = self.class.generate_uuid if uuid.blank? }
validates :uuid, presence: true, uniqueness: true

define_method :to_param do
uuid
end

define_method :uuid= do |val|
raise UuidChangeError, 'Uuid changing is bad idea!' unless new_record? || uuid.blank? || uuid == val
module_function

super(val)
end
end
end

def short_uuid
UUIDTools::UUID.parse(uuid).hexdigest
end

def self.generate_uuid
def generate_uuid
SecureRandom.uuid
end
end

ActiveSupport.on_load(:active_record) do
ActiveRecord::Base.send(:include, Uuidable)
end
require 'uuidable/migration'
require 'uuidable/active_record'
34 changes: 34 additions & 0 deletions lib/uuidable/active_record.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
module Uuidable
# ActiveRecord mixin
module ActiveRecord
extend ActiveSupport::Concern

class UuidChangeError < Exception; end

# ClassMethods
module ClassMethods
def uuidable
after_initialize { self.uuid = Uuidable.generate_uuid if uuid.blank? }
validates :uuid, presence: true, uniqueness: true

define_method :to_param do
uuid
end

define_method :uuid= do |val|
raise UuidChangeError, 'Uuid changing is bad idea!' unless new_record? || uuid.blank? || uuid == val

super(val)
end
end
end

def short_uuid
UUIDTools::UUID.parse(uuid).hexdigest
end
end
end

ActiveSupport.on_load(:active_record) do
ActiveRecord::Base.send(:include, Uuidable::ActiveRecord)
end
2 changes: 1 addition & 1 deletion lib/uuidable/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module Uuidable
VERSION = '0.0.1'.freeze
VERSION = '0.0.2'.freeze
end

0 comments on commit f98aa88

Please sign in to comment.