Skip to content

Instantly share code, notes, and snippets.

@odigity
Created July 26, 2012 13:13
Show Gist options
  • Save odigity/3181983 to your computer and use it in GitHub Desktop.
Save odigity/3181983 to your computer and use it in GitHub Desktop.
Given: An Account model in the database with a :name field. A list of account objects with names like "Accounts Payable" which are human-readable.
Need to: Be able to reference specific accounts by name in your business logic. For example, let's say you define a method that records a petty cash expenditure:
def spend_petty_cash
Account.find('Petty Cash').credit(20)
Account.find('Expenses').debit(20)
end
It's error prone and inelegant to use human-readable strings directly in your code everywhere to identify an account (with capital letters, spaces, and who knows what else, since they're defined by the accountants, not programmers). So, it would be useful for this - and provide additional benefits - to have a config file with something like:
Account.register << [
{ petty_cash: 'Petty Cash' },
{ expenses: 'Expenses' },
{ taxes_12_4: 'Taxes for Q4, 2012' }
]
That works for static account names, but what if you dynamically create one account per employee, with a naming convention? Like:
'Payroll - Jack Smith'
'Payroll - Jane Doe'
One way to solve this is to allow string formatting placeholders in the string, and then use positional args to do the lookup:
Account.register << [
{ payroll: "Payroll - %s" }
]
Account.custom_find( :payroll, 'Jack Smith' )
And the custom_find method can use the ruby % operator to fill in the values (http://ruby-doc.org/core-1.9.3/String.html#method-i-25). But named args would be better than positional args:
Account.register << [
{ payroll: "Payroll - #{name}" }
]
Account.custom_find( :payroll, name: 'Jack Smith')
But I don't know a technique other than eval to implement this or something like it.
Lastly, it would also be nice to take that same config info in the Account.register block and turn them into regexs. For example:
/^Payroll - .*$/
Which could then be used by a rake task that looks at all the accounts in the database and ensures that a) all accounts in the config file have been created and b) all accounts in the database match the specs in the config file, or else are deleted. That way you can modify the config file, push a new release of your app, run the task, and it removes accounts that are no longer wanted and adds the new ones, like a migration, but for data.
But I have no idea how to use the same config data to generate both the account finder method logic and the regexes for the rake data maintenance task.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment