How to Automatically Check Resource Creation in Rails? - ruby-on-rails

So I'm building an ecommerce project in Rails that uses dynamic pricing for the items - purchasing something increases the price, and when an item isn't purchased for a certain amount of time the price drops.
I could do this manually at an arbitrary but consistent time, but I would really like to run at least the checking automatically. So far the only automation libraries/tools I've found for Rails have been test related, and because this relates directly to resources in Rails, I wasn't sure it made sense to search for a way to do this in Python.
In my project, the resource is called a Purchase and has relationships to the User and Item objects. What I envision is being able to search through all Purchase objects created in the last 24 hours. Doing it the other way round (going through all Items and their associated transactions) seems like a runtime nightmare, so I assume that's not even an option.
I'd be happy to post any code that would help. Thanks!

you have after_create callback ActiveRecord where you can increase the price. How to reduce price is more complex question, you need a job to run periodically and check for all Purchases.
How to get all related resources Shannon described quite well.

Related

Structuring a Rails App to work with Remote Database via API

I am about to embark on the creation of one of my first meaningful rails apps, and am a bit unsure of how to structure things.
Here's my situation. I am using a SAAS inventory software that keeps track of approximately 4000 products. I need an app that can perform routine maintenance functions on the products. For example, to give you an idea:
Every week, calculate and set the "low stock alert quantity" for each product based on historic sales
Assign products to product categories based on rules (i.e. if the word "t-shirt" is in the title, automatically add it to the t-shirts category)
etc etc
My questions are as follows:
I'm not sure exactly how to structure the data in this app. Should I query the API each time I need to retrieve the products? Or should I build a local copy of the inventory in a local database, for faster querying? If I am to build a local copy of the database, what would be an efficient way of keeping an up to date version of each product without consuming too much server resources? Obviously I can't pull 4000 products via the API at once...and I also don't want a cron job to be running every minute of the day.
Where should I place the code for my remote API functions? Do I create a class, module, or something else?
Thanks for any advice.
First of all, do you really need a web interface? I don't see so in your app description. If what you want to build is a maintenance set of tools that would be executed periodically, why would you use Rails?
The way of structuring data depends on your needs and resources. Does your SAAS provide instant notifications on products update, such as webhooks? Does your SAAS API let you fetch only products that were updated after a certain date? What's more important to you, speed or working with up to date data? Answering those questions to yourself should help you to decide what the best approach is.
Regarding the app design, it looks that you could write a gem where you could have different modules to manage data, execute operations with that data and connect to the third party service, and use that gem in scripts that would execute periodically. I would recommend you reading a book on Object Oriented design that I truly believe it'd help you, Practical Object-Oriented Design in Ruby.
Just one last word, I'm taking too many assumptions here, no one but you know better your requirements, and the design of your software depends on that.
If your API follows REST then it can very easily be integrated into rails using ActiveResource. If the API is more complicated, you could use ActiveModel and roll your own implementation. Just create a base class of your own that handles connection and authentication and extend your models from that. Given the limited description of your problem, there's not much more I can say.

Pseudo constants that very rarely need to change on runtime in a web app

So I'm asking the question in the context of Rails, although it shouldn't really matter.
On my web app I have something like a monthly subscription fees and other prices that is right now hard coded as a constant in a class.
However, the person managing the site will want to be fiddling with the prices and numbers once in a while, and it doesn't seem right that he has to go into the code, change it, push it to the server etc.
So I guess you store it in the database as a single row in a constants table.. but I don't know.. Is this the right way of going about it? What does public wisdom dictate?
It depends how much you trust the person running the site.
However, in the case of subscription fees, I recommend a plans table so that you can 'grandfather' people to old plans when you change the price, as well as give different price options, and even track history and plan changes for a given customer. Think of it like accounting - you want as much information in the database as possible.
For other constants, it depends how often you're changing them and what they're for, and how much you trust the person running the site to not break things (does the site have tests and CI?).
I think thats ok. An alternative would be using environment variables...

Credit system: history based or balance based?

I am going to write a simple credit system that user can "add", "deduct" credits in the system. Currently I am thinking of two approaches.
Simple one: Store the user' credit as balance field in the database, and all actions ("add", "deduct") are logged but not used to compute the latest balance.
History based: Don't store the balance in database. The balance is computed by looking at the history of transactions, e.g. ("add", "deduct")
Both case would works I think, but I am looking to see if any caveat when designing such a system, particularly I am favoring the History based system.
Or, are there any reference implementation or open source module I am use?
Update: Or are there any Ruby/Rail based module like AuthLogic so I can plug and play into my existing code without reinventing the wheel (e.g. transaction, rollback, security etc)?
Absolutely use both.
The balance-based way gives you fast access to the current amount.
The history-based way gives you auditing. The history table should store the transaction (as you describe), a timestamp, the balance before the transaction happened, and ideally a way to track the funds' source/destination.
See the Ruby Toolbox for bookkeeping and Plutus double-entry bookkeeping gem.
In addition, if your credit system may affect users, then I recommend also using logging, and ideally read about secure log verification and provable timestamp chaining.
For logging details see: techniques for ensuring verifiability of event log files.
For open source code that does credit, you may want to look into: http://www.gnucash.org/
Adding and deducting credits implies that you might also need to be aware of where these credits came from and where they went. Any time you get into a situation like this, whether it is with currency or some other numerical quantity that needs to be tracked and accounted for, you should consider using a double entry accounting pattern.
This pattern has worked for centuries and gives you all of the functionality you need to be able to see what your balances are and how they got to be that way:
Audit log of all transactions (including sources and sinks of "funds")
Running balance of all accounts over time (if you choose to record it)
Easy validation of the correctness of records
Ability to "write-once" - no updates means no tampering
If you aren't familiar with the details, start here: Double Entry Bookkeeping or ask anyone who has taken an introductory course in bookkeeping.
You asked for a Ruby on Rails open source solution that you could plug and play into your application. You can use Plutus. Here is an excerpt from the description of this project on Github:
The plutus plugin provides a complete double entry accounting system
for use in any Ruby on Rails application. The plugin follows general
Double Entry Bookkeeping practices. ... Plutus consists of tables that
maintain your accounts, entries and debits and credits. Each entry can
have many debits and credits. The entry table, which records your
business transactions is, essentially, your accounting Journal.
yes, use both.
On top of that, you'll sometime need to reverse a transaction/
transactions.When doing that, create a new reversed transaction to
notate the money transfer.
sometimes, You'll need to unify several transactions under one roof. I suggest to create a third table called 'tokens' that will be the payments manager and you'll unify those grouped transactions under that token.
token.transactions = (select * from transactions t where t.token = "123") for example

Document-oriented database (MongoDB?) and invoicing/ordering?

New to document-oriented database concepts and have a few high-level questions related to orders and order processing.
How does one capture an order in this world? Would an order just be a new document in an Orders collection? Would order_item relate back to a product listed in another document? Or is it assumed that order_item would be copied and inserted into the order document and thus, perhaps, difficult to report the total of product sold over time?
How does one work around lack of transactions and maintain integrity
Sorry, very new to me though eager to understand...it sounds very appealing to encapsulate all these 'things' for sale as "objects" and move them around as such between server & clients, etc...if it's indeed plausible. Just need some help conceptualizing big picture dos and don'ts.
How does one capture an order in this world? Would an order just be a new document in an Orders collection?
Yes. That's the way these databases work.
Would order_item relate back to a product listed in another document?
It could. Depends on what you're doing.
Or is it assumed that order_item would be copied and inserted into the order document
Also possible. This works well for historical analysis and data warehousing.
and thus, perhaps, difficult to report the total of product sold over time?
It's always hard to report total product sold over time.
Today, product "23SKIDOO" is a 23l, open-valved, framistat with double widgets.
Last year, before the recall, the same product was a 23l, closed-valved framistat with only a single widget.
In a previous year, the same product was actually 22.5l.
Are these the "same" product? Marketing calls them all "23SKIDOO". But there are differences.
A single Product table doesn't resolve this correctly. What folks then do is invent product lines and product families so they can introduce the "23SKIDOO-B" and "23SKIDOO-PLUS" products which are all part of the "23SKIDOO" family.
Product lines and product families and other more fanciful groupings are workarounds and hacks to magically make unrelated products report together and provide a "total product sold over time" even though the products are clearly different.
Copying the product into the order (while it seems wasteful) can preserve more historical fidelity than many of the commonly-used workarounds.
How does one work around lack of transactions and maintain integrity?
MongoDB has locks. http://www.mongodb.org/display/DOCS/How+does+concurrency+work.
It's not clear what you mean by lacking transactions.
So its always hard to answer a generic question. However, what I would encourage you to do it look at the patterns of read and write you expect your application to perform. There are trade offs for certain document designs just like there are from RDBMS schema designs.
Here's a link to a MongoDB centric schema design presentation. It may help you to understand some of these trade off and options for design.
http://www.scribd.com/doc/47326395/MongoBoulder-Schema-Design

BDD, what's a feature?

I'm just starting with BDD and I'm trying to build a small app, so I can see it working in a real environment, but I'm having trouble deciding what should be a feature. I'm building a tiny shop.
I decided that "Compare products" will be a feature and "User can checkout as guest" will be one, but to get to that, I first need to list products.
My question is, should "There should be a list of products" be a feature?
Thanks!
It should probably be a feature, but try wording it from a user's point of view. What does this list of product offer him?
User should be able to get an overview of offered products
User should be able to order and reorder products on name, price, availability.
It's pretty hard to begin doing BDD. The only thing that helps feeling confident in your abilities and the whole approach is to write test scenarios and the code that executes them. I would suggest you not to make already complex and confusing situation harder. Pick whatever task that you need to implement, open a blank text file and try to explain using simple sentences the behavior. Every sentence should start with one of three keywords: given, when and then. Using your favorite BDD framework write the code that will parse these sentences and stimulate the application to get into the start state (given), execute some commands (when) and assert the transitioned state (then). Application code may start from mere mocks. Replace gradually those mocks with gradually built code and grow your application with higher confidence and quality levels.
User story is a feature. Something that can be expressed in format:
As role
I would like to do something
So that goal
E.g.
As user
I would like to be able to compare products
So that I can select a product satisfying my needs in a best way
As guest
I would like to checkout my shopping cart
So that I can complete the purchase
Each feature have to be confirmed by a series of Given-When-Then scenarios of course.
You're basically asking what is a feature. Think about it, you have a story, a story describes a feature you (or other people involved) want for your app. Usually it has the form of: As a user I want to view list of products. You may add notes to this story, in order to make it more clear. But then comes the specific behaviour (that eventually you will test against) - there are infinite number of behaviours that conform to this story (think about view of products and the many ways to present them). Your focus, in BDD, is on finding the behaviour that suite your app needs (I use app and not user, because sometimes you should decide for the user) - by talking to as many people as you can, by trying stuff out and iterating it over.
It's like going from top to bottom - always trying to focus on behaviour - being more specific as you go. If you think about it, given a behaviour (meaning a set of tests) there is an infinite number of implementations. That's why the focus of BDD is to truly understand the behaviour by experimenting and talking - there is always a degree of freedom.
More important would be to figure out what the user wants to do with the list of products?
the feature would be providing something valuable to the user.
so in your case it would be
Choose a product to view from a list of products
Choose x products to compare from a list of products
Others
I would classify a feature as a minimum useful set of stories that deliver some coherent (business) value.
for BDD framework see http://kernowcode.wordpress.com
To determine, if a requirement is an explicit feature / user story, you could use the guidelines of task based design / documentation (e.g. http://www.sprez.com/articles/task-documentation-design.html). Such concepts acknowledge that a user of a system wants to achieve a specific result. Usually, to know something (such as: which products are available) is only a step in the process of purchasing / selling / building / etc.
A good starting point in BDD is to write the topics you would use as chapters in your user manual. These topics are usually the features you are going to provide in your software solution.
A nice framework that supports such an approach of specification-by-example is Concordion (http://concordion.org). Please have a look at the description of “acceptance tests in plain English” (http://gojko.net/2009/09/01/acceptance-testing-in-plain-english-with-concordion-net/).

Resources