开发者

Delegating ActiveRecord objects with plain ruby objects

开发者 https://www.devze.com 2023-02-07 02:57 出处:网络
I want to be able to have a TestUser model specifically for development and test which acts entirely the same as my normal User model, except that it always authenticates.

I want to be able to have a TestUser model specifically for development and test which acts entirely the same as my normal User model, except that it always authenticates.

The key issue here is to have TestUser always call class methods on User and look up it's class level instance variables as though it were a normal User, and not do it through cattr_accessor i.e.:

class User
  class << self
    attr_accessor :foo
  end
end

class TestUser ?< ??
  ??
end

---
User.foo = 'bar'
TestUser.foo => 'bar'
User.new.authenticate?('password') => maybe, runs authentication
TestUser.new.authenticate?(_) => true

I know I could do what I want by just extending User in test and development to always a开发者_如何转开发uthenticated, but I was wondering if it would be possible to do it with that extra class.


I wouldn't waste any time on this, if you aren't going to use it in production.

You have tests that allow you to "always authenticate a user", but why waste time on this nice to have problem, when you could be coding towards your end goal, to get this out faster/stronger/better ... whatever your goal is.


class TestUser < User
  def authenticate?
    true
  end
end

But you should really use tests/rspec if you are just testing your code.

And you can use: cattr_accessor :foo for accessing class variables.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号