Sha256: be33c748701991dc74ef58316275848b5ec701f978678b647c4d9aa0b583bdc6

Contents?: true

Size: 1.79 KB

Versions: 2

Compression:

Stored size: 1.79 KB

Contents

require 'rails3_artifactor'
require 'logging_assist'

module DataMapper 
  module Generators
    class RolesGenerator < Rails::Generators::NamedBase      
      desc "Add role strategy to a model" 
      
      class_option :strategy, :type => :string, :aliases => "-s", :default => 'role_string', 
                   :desc => "Role strategy to use (admin_flag, role_string, roles_string, role_strings, one_role, many_roles, roles_mask)"


      class_option :roles, :type => :array, :aliases => "-r", :default => [], :desc => "Valid roles"

      def apply_role_strategy
        logger.debug "apply_role_strategy for : #{strategy} in model #{name}"
        begin
          insert_into_model name do
            insertion_text
          end
        rescue
          say "Model #{name} not found"
        end
      end 
      
      protected                  

      extend Rails3::Assist::UseMacro
      use_orm :data_mapper
      include Rails::Assist::BasicLogging

      def orm
        :data_mapper
      end
  
      def default_roles
        [:admin, :guest]        
      end
  
      def roles_to_add
        @roles_to_add ||= default_roles.concat(options[:roles]).to_symbols.uniq
      end
  
      def roles        
        roles_to_add.map{|r| ":#{r}" }
      end
  
      def role_strategy_statement 
        "strategy :#{strategy}, :default\n#{role_class_stmt}"
      end

      def role_class_stmt
        "  role_class :role" if [:one_role, :many_roles].include? (strategy.to_sym)
      end
  
      def roles_statement
        roles ? "valid_roles_are #{roles.join(', ')}" : ''
      end
  
      def insertion_text
        %Q{include Roles::#{orm.to_s.camelize} 
  #{role_strategy_statement}
  #{roles_statement}}
      end
  
      def strategy
        options[:strategy]                
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
roles_data_mapper-0.2.0 lib/generators/data_mapper/roles/roles_generator.rb
roles_data_mapper-0.1.3 lib/generators/data_mapper/roles/roles_generator.rb