Consider the following scenario: You have an app that you’re working on and you have a QA team that goes through certain scenarios to test the app and its functionality. Some tasks have to be done manually, others can be helped by pre-existing data such a as a user whose trial has expired. For that we want to seed the DB with a user who signed up and whose trial expiration date has passed. It’s very common problem, which is why Ruby on Rails comes with a seed functionality baked in.
BUT… there are many of these kinds of scenarios, and creating and maintaining the seed code can be tedious. So you want to structure your code in a way that is maintainable. You come up with something like this:
def seed_user hash
if User.where(username: hash[:username].downcase).exists?
User.where(username: hash[:username].downcase).first
else
User.create hash
end
end
user_defaults = {
administrator: false,
name: 'No Name',
password: 'password',
trial_expiration: Time.now + 30.days,
username: 'foo',
}
######################################
# Admin User
######################################
user_specifics = {
administrator: true,
name: 'Admin User',
username: '[email protected]',
password: 'admin',
}
user_params = user_defaults.merge(user_specifics)
admin_user = seed_user user_params
######################################
# Expired Trial User
######################################
user_specifics = {
name: 'Expired Trial User',
username: '[email protected]',
password: 'expiredTrial',
trial_expiration: Time.now,
}
user_params = user_defaults.merge(user_specifics)
expired_trial_user = seed_user user_params
expired_trial_user.update trial_expiration: user_specifics[:trial_expiration]
# It's necessary to update the trial expiration attribute because the user creation process sets it automatically (in order to avoid people being able to pass it on and cheat).
#... about 10 more scenarios like this.
Looks straight forward doesn’t it?
Great. So we got that out of the way, but now it’s 6 months later and we’ve made an update to our model. We’ve added the concept of a payment subscription where we have a Payment model that can be associated with the User model and that payment object holds all the necessary information related to it. We don’t need to go into more detail about that structure for now. What we do know is that we now have to update our seeds. So we update the user_defaults hash to look like this:
user_defaults = {
administrator: false,
name: 'No Name',
password: 'password',
trial_expiration: Time.now + 30.days,
username: 'foo',
payment: Payment.new(payment_defaults),
}
You don’t need to worry about what payment_defaults is, just know that it’s some default values for the attributes related to the Payment model. Alright, so you are proud of yourself that you only had to add 1 line of code to support the new structure. You give yourself a pat on the back. Then a few minutes later, as you’re peeking into the development DB to check that everything look right, you notice that the 10s of users you created through the seeds all have the same payment_id. That’s not right!
It makes sense though, doesn’t it? The defaults hash got evaluated and the values set after the first use of it and then all of the users inherited the same defaults. So the same way they all will have the same trial_expiration date, they will also have the same Payment object. Hmmm… so what can we do now?
The first thought that comes to mind is to move the payment info from the default hash to the user_specifics hash. That way each user will have its own value. This will definitely solve the problem, but it doesn’t feel right. There has to be a way in Ruby where we can set values in a Hash to be dynamic. After all, we can do it for the keys (eg. hash = {}; hash[key_name] = value) so why not for the values?
Turns out there is not a built in way in Ruby to do this. There are a few posts out there on how to achieve this, but most resort to monkey patching the Hash class or created a new subclass, like the answer in this SO question:
class HashWithThunkValues < Hash
def [](key)
val = super
if val.respond_to?(:call)
# Force the thunk to get actual value.
val = val.call
self[key] = val
end
val
end
end
or this other answer in the same question:
class LazyHash < Hash
def [] key
(_ = (@self||{})[key]) ?
((self[key] = _.is_a?(Proc) ? _.call : _)) : super
end
end
We don’t want to do all of that just for our seeds. Seems like overkill. Although, we might still be able to use these solutions to create our own. The idea of using a Proc or lambda as the value is what we want. So let’s update our defaults hash to:
user_defaults = {
administrator: false,
name: 'No Name',
password: 'password',
trial_expiration: Time.now + 30.days,
username: 'foo',
payment: -> { Payment.new(payment_defaults) },
}
If we leave the code as is, we’ll see the following error when we try to run the seeds:
NoMethodError: undefined method `primary_key' for Proc:Class
That’s because Rails is trying to set the payment association to the value of the :payment key in the hash, which is currently a Proc when it expects an ActiveRecord model. To make this work, we need to make sure the Proc is executed by calling the call() method on it. My initial instinct was to do it in place:
user_defaults = {
administrator: false,
name: 'No Name',
password: 'password',
trial_expiration: Time.now + 30.days,
username: 'foo',
payment: -> { Payment.new(payment_defaults) }.call,
}
But that takes us back to the original problem we’re trying to solve since all of the users will get the same value. And we decided that we’re not going to monkey patch the Hash class. So we need add it somewhere else. Since we already defined a function that we use to seed the users, that is the easiest place we can add this in:
def seed_user hash
if User.where(username: hash[:username].downcase).exists?
User.where(username: hash[:username].downcase).first
else
hash[:payment] = hash[:payment].call if hash[:payment]
User.create hash
end
end
In our case, we know exactly which part of the hash is a Proc and which isn’t. We could theoretically look through each key and check the value to see if it’s a Proc and then call the call method on it. That would be more dynamic. But again, it’s a bit of an overkill for our use case. If it’s simple and it works as is, then the answer to any other optimization is YAGNI. Once you do have a reason to refactor it, then how you would do that would be determined at that time. Whereas at this particular moment, YOU AIN'T GONNA NEED IT!
Now, when we run the seeds, we do see that a new Payment object is created for each user, and each user has a unique payment_id. All it took was 2 new lines of code, the one in the hash and the one in the seed_user method. With these 2 lines of code we are able to create dynamic users with unique values for our seeds.
Have you needed dynamic hashes in your application? Share with us your use cases and how you solved them, we’d love to hear how others have tackled this problem.