views:

323

answers:

1

Hey guys,

I want to extend Class Role such that I can add more roles to the roles table in Spree. My application would have different prices based on roles.

By default roles have: ("admin" and "user") in it. I want to add more types to the table.

Q1: Can I just extend the Role class in one of my extensions? Q2: How can I implement (actually extend on app/models/Variant.rb) the prices based on different roles such that it just grabs price from one place? So that I dont have to change code in *_html.erb files where its using price.

If I can get this to work this would be a cool extension to have on github.

Thanks

+1  A: 

To extend classes in Spree, you can use Modules or class_eval. Spree extensions tend to use class_eval. Here's an example for extending User and Variant in a custom extension.

class CustomRoleExtension < Spree::Extension

  # main extension method
  def activate

    # extend User
    User.class_eval do
      def business?
        self.roles.include?("business")
      end

      def sponsor?
        self.roles.include?("sponsor")
      end

      def developer?
        self.roles.include?("developer")
      end
    end

    # extend Variant
    Variant.class_eval do
      def price_for(role)
        # ...
      end
    end
  end

end

To add more roles, I just added a defaults/roles.yml to my extension, with custom yaml blocks:

coach_role:
  id: 3
  name: coach

trainer_role:
  id: 4
  name: trainer

graduate_role:
  id: 5
  name: graduate

Then when you run rake db:bootstrap, it will add all those roles to the database.

Let me know if that works.

viatropos
Can you give full paths (in relation to webroot)? I'm still working out where to put what.
Elizabeth Buckwalter
Oh and can't you extend the model in the your_extension/app/models/user.rb file?
Elizabeth Buckwalter
viatropos, sorry for the crazy late reply but, yes, it worked. Thanks.
elgrancid