Best practices concerning SQLite queries, Sinatra, and erb? - ruby

I'm building a framework that allows users to install apps to add specific functionalities. The intent is for the user to manage these apps through a small web app. The list of installed apps exists in a sqlite3 database, and I'm using Sinatra to route http requests. I'm using erb templates to design the web pages in question.
My question is, what is the best practice for populating my displayed list of installed apps? Should I make the SQL queries in the Sinatra 'do' block and then pass an array containing the app names over to the erb? Or should I be making the database queries in the erb file itself?
Functionally, I'm sure they are very similar (though if there are functional differences, I'd like to know), but I would like to be following best practices if at all possible :)

The best practice consists in doing your SQL queries in the do block, and passing an object to your template.
It is considered a bad idea to write too much code in the templates, and it can be useful to isolate the fetching logic from the displaying logic if you ever want to use the same template from different routes.
By using Ruby's duck typing, you can make your template very flexible. For instance with Haml:
%ul
- #dataset.each do |row|
%li= row['name']
All you need to do is to provide the template with an Enumerable of objects which all respond to []. It can be the result of a database query (most gems return something compatible, I think), or it can be an hard-coded Array of Hashes for instance.

Related

Should views be rendered by the app, or should a static site contact the API using AJAX?

I am starting to write my first web app with Node.js and Express. I have two approaches in mind.
Create two sets of routes. One that sends JSON, one that renders the page using a templating engine
Create a static website that makes API calls to the backend using AJAX, and have only routes for the API.
I understand that approach #2 depends on AJAX support in the browser, but if this was your project, based on the advantages and disadvantages of each approach, which would you choose and why?
If I am reading it right, both options #1 and #2 first set of routes is an API that returns JSON rather than sends it.
Assuming that in #2 you wouldn't create static pages with JavaScript doing AJAX calls, but rather still use express static routing like app.use('/', express.static(path.join(__dirname, 'dist'))); the difference between 2 approaches isn't that big.
Unless you already know some supported template language, such as mustache the cons are that you have to learn one and before that pick one (which isn't always an easy task from my experience!).
If you don't know one, depending on your application, you might still benefit from learning and using one. As an example you can think of a very generic UI where a single template could be reused very many times - like a generic database UI similar to, say well known phpmyadmin.
In case of static routing, you can achieve similar results by using a JavaScript framework which has components or templates, such as angular. If you aren't planning to use one, that could result in a lot of code duplication of otherwise re-usable widgets. And even when using one I can imagine a case when template engine would result in less code (or less files in your project at the very least). Not sure though if it's going to be easier to navigate and moreover to cover with tests when the project grows.
Without knowing more about your project it is hard to give more advice.
If the product you're developing is primarily static content with some dynamic pieces here and there, I'd recommend serving HTML from your backend via a templating system. A good example of this would be a blog. You'll end up with better SEO and there are less moving pieces to grok in this approach.
However, if you want to develop a single page application, I recommend using your backend entirely as an api, and writing your client side logic entirely in React/Vue/Angular/whatever. Single page applications have their front ends written entirely in javascript, and are best suited to highly dynamic, "app like" experiences online. Think gmail or facebook.
In my current project we use both approaches. Many views are static and data is obtained from API calls (we just use angular) or bootstrapped values (we load some objects with template, like user roles etc.)
However, some views are rendered on server site, because it easily allow us to dynamically inject values, tokens or other supporting data without making extra requests.
So, I vote for flexibility

How to test/spec Sinatra & MongoDB API with Cucumber?

I want to spec a Sinatra server that receives HTTP requests, stores things in MongoDB, and responds with JSON. How would I spec both the MongoDB entries and the responses?
I'd like to use Cucmber and RSpec to do this cause I hear they're hot, but I'm not really good with them yet.
My learning so far with BDD is that you need to think in very small steps. E.g. you could start in making specifications with rspec for your routes, example project with sinatra here, and another example, here.
Then you could start in making specifications for your model layer. Small steps also here, check for validations, setting and getting attributes.
Last, you might approach to specify the view, here you need to learn about mocks and stubs for your controller and models.
Cucumber is a different story in my view. You need to write cucumber specifications when you work with your customer, to understand together the requirements of your app. It facilitates acceptances testing as far as I can see.

Is WordPress MVC compliant? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Closed 7 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Some people consider WordPress a blogging platform, some think of it as a CMS, some refer to WordPress as a development framework. Whichever it is, the question still remains. Is WordPress MVC compliant?
I've read the forums and somebody asked about MVC about three years ago. There were some positive answers, and some negative ones. While nobody knows exactly what MVC is and everybody thinks of it in their own way, there's still a general concept that's present in all the discussions.
I have little experience with MVC frameworks and there doesn't seem to be anything about the framework itself. Most of the MVC is done by the programmer, am I right? Now, going back to WordPress, could we consider the core rewrite engine (WP_Rewrite) the controller? Queries & plugin logic as the model? And themes as the view? Or am I getting it all wrong?
Thanks ;)
Wordpress itself is not architected in MVC, but one can build very MVC oriented themes and plugins within the framework. There are several tools which can help:
WordPress MVC solutions:
Churro: # wordpress.org/extend/plugins/churro
Tina-MVC: # wordpress.org/extend/plugins/tina-mvc
Plugin Factory: # wordpress.org/extend/plugins/plugin-factory
MVCPress: http://mozey.wordpress.com/2007/01/22/mvcpress-screenshots/#comment-3634 (abandoned, but interesting ideas)
MVC threads on WordPress.org Ideas and Trac:
http://wordpress.org/extend/ideas/topic/mvc-plugin-framework
http://wordpress.org/extend/ideas/topic/complete-reestructuring
http://wordpress.org/extend/ideas/topic/rewrite-wordpress-using-mvc
http://wordpress.org/extend/ideas/topic/wordpress-theme-revamp (more on XSL than MVC)
http://core.trac.wordpress.org/ticket/12354 (on MVC in widgets)
Wordpress is kinda-sorta MVC. If anything it is a pull-type MVC layout, where the View 'pulls' data from the model. It does this in a very proceedural way, instead of using lots of different objects, but this actually makes the front end templates easier to write in a lot of ways.
This also gives the views some degree of controller logic (thus the kinda-sorta MVC).
Lets run this down:
Wordpress gets a URL. The wordpress core acts as a controller and determines what initial queries to run of the database, and by extension, what view should be loaded (category view, single post or page view, etc). It then packages that INTIAL query response and sends it to the view file.
That view file CAN be a strict display only file OR it can request additional information/queries beyond the built in one. This is the pull-type of the MVC, where the view pulls data from the model instead of the controller 'pushing' data from the model into the view.
Thus, when the view sees code to load a sidebar or widget area, it asks for that information. However, what widgets should be there is determined by the controller, which looks at the model for what widgets are in the sidebar, and then selects those that are set to show on the current page, and returns those to the view.
That each part of that isn't an object doesn't make this any less MVC. You can alter WP core without (necessarily) altering anything about a theme. Similarly, as long as you use built in functions like 'get_pages()' then the model and the database tables could change as long as those functions still returned the right data. So, the model is independent of the view, and the controller is independent as well (except when the view adds controller logic to do more than the core normally does).
While you COULD have a model object holding a number of methods and stuff like WPModel::get_pages('blah blah'), and contain everything that way, there is still fundamental separation of concerns.
View: template files
Controller: WP core
Model: the various functions that handle specific data handling.
As long as the names, arguments, etc, stay the same (or just have new ones added) then separation of concerns is maintained and one can be altered without disturbing the others.
It isn't a super-clean version of MVC, (especially when hooks get involved), but at a basic level it starts there.
And being proceedural about it isn't a bad thing IMO. A request from a website is pretty inherently proceedural: it is a process with a clear beginning and end, and just needs a procedure to process the request, get data, package it, then die. You can set up those steps with objects and object methods and OOP layouts (which would make some things easier) or you can just write alot of function calls and separate them out that way. Class members like private variables are lost that way but depending on the needs of the application... you might not care.
There is no one-grand-way to do development, and WP sits at like 20% of websites so it is doing something right. Probably something to do with not making people have to learn/memorize complex class hierarchies to get the database to answer the question 'what pages are child of page x?' and deal with that data. Could you make it that easy with OOP? yes, but if Joomla is any example of how hard it is to implement a complex custom website with OOP, then WP is FAR easier and quicker, and time is money.
As already mentioned in the comments, MVC is an architectural design pattern, not a specific framework, and no, Wordpress doesn't follow the MVC pattern.
There is a separation of views (templates) from the programming logic, but only in the frontend, not in the admin panel and a general separation of views and application logic is not inevitably MVC. An implementation of the MVC pattern usually assumes some kind of object oriented programming paradigm behind it and Wordpress is mainly implemented in a procedural way, with plain SQL queries in the PHP functions, therefore not having an actual model either.
One of the topics that periodically crops up in discussions as it relates to WordPress is the idea of WordPress and MVC.
But the thing is that MVC is not the silver bullet of web development that we try to make it out to be. Yes, it’s an awesome design pattern, and I personally think that it fits the web application model like a glove, but not every framework or platform implements that design pattern.
Case in point: WordPress is not MVC.
And that’s okay. I think we need to leave the desire of trying to shoehorn it into our projects aside especially when the pattern WordPress provides is not only sufficient, but works well when leveraged correctly.
“But I Love MVC!”
So do I! In fact, I spent the last year working on a project that more-or-less mimicked the MVC architecture.
A high-level example of MVC.
A high-level example of MVC.
For example:
Views were implemented using templates
Controllers were implemented by a combination of using function names like create, read, update, destroy, delete, and so on (even though these functions were hooked into the WordPress API
Models were functions also were called to validate and verify data prior to serializing the data. Again, this required that certain functions be hooked into WordPress to achieve the desired result.
Finally, a set of rewrite rules gave the application a clean set of predictable URLs in the format of /people/update/1 or /people/all.
What Pattern Does WordPress Implement?
WordPress implements the event-driven architecture (of which there are several variations such as the Observer Pattern).
In short, you can conceptually think of this as the following:
Things happen when WordPress is processing information.
You can register your own function to fire when these things happen.
Not too complicated, is it?
A high-level example of event-driven patterns
A high-level example of event-driven patterns
When you begin to think in terms of the paradigm in which it works rather than trying to make it work the way that you want it to work, it’s liberating. It helps to solve problems much more easily.
The bottom line is this: WordPress implements the event-driven design pattern, so even if you end up trying to implement MVC, you’re still going to have to utilize the hook system.
If you’re not careful, you can end up trying to craft the perfect architecture without actually getting your work done, and thus end up finding yourself so high up in the atmosphere of software that you’ve effectively become an architecture astronaut.
So You’re Saying Avoid Design Patterns?
Not at all! Design Patterns serve a purpose because, above all else, they basically give us solutions to previously and commonly solved problems. Use them!
But the point I’m trying to make is that we don’t need to try to force things to fit pattern just because we like the pattern. That’s not their purpose. Instead, leverage the primary pattern that your platform of choice implements – in our case, it’s an event-driven pattern – and then implement patterns where they fit (such as dependency injection or something like that).
Otherwise, it’s like trying to put your foot in a glove.
Courtesy (and totally copied :P) from : http://tommcfarlin.com/wordpress-and-mvc/
Just to update this with more recent information for people hitting this from search engines - the wp-mvc plugin http://wordpress.org/extend/plugins/wp-mvc/ goes a long way to creating a mvc framework for plugin development. You can find out more here: http://wpmvc.org/documentation/70/tutorial/
Just to add to the list of options, (I'm admittedly biased as the author,) swpMVC is a fully featured, lightweight MVC framework, inspired by Rails, Sinatra, Express, and FuelPHP. It's thoroughly documented, and while I have used and enjoyed wp-mvc, I wanted something where the models were able to populate views themselves, including form controls for interacting with said models.
I put this together largely to reduce the amount of controller code required to put together an app on top of WordPress, and the result is a very fast and effective framework that runs inside WordPress. The models are based on PHP Activerecord and 8 models are included for existing WordPress data types, including Post, PostMeta, User, UserMeta, Term, and a few more. Modeling data is very easy thanks to the activerecord library, and I've enjoyed working with this framework immensely thus far.
Also ships with underscore PHP and PHP Quick Profiler (as seen in FuelPHP.)
RokkoMVC is a micro MVC framework built especially for WordPress. The project is meant to simplify AJAX functionality in WordPress applications, as well as bringing in all the other benefits of using models, views, and controllers to your theme.
I had a bash recently at creating a plugin that makes use of a simple view-controller system, and quite liked the results, so I separated the template stuff out to its own repo. It offers object-based controllers, passing variables locally to PHP templates, template fragments (templates within templates) and components (template fragments with their own sub-controller). All in two tiny classes!
Of course, I wrote this code thinking that no other WP developer had considered the problem before ;-).
It's far from mvc, there is no kinda-sorta thing like some people say, it's either MVC or not... The fact that you write logic on the view level doesn't qualify it as a mvc framework. The reason people use it - it's easy to learn, you don't need to be hardcore php programmer, they're lazy.

How to create a REST API for a Ruby application?

I would like to know how to provide a Ruby application with a REST API. I could code something based on Ruby's TCPServer API, but that seems a bit low-level. Do you think it would be a good solution? Or do you recommend a better approach?
You can use Sinatra to write tiny, focused web applications and lightweight REST services very quickly.
In the documentation section they highlight a couple of videos on that matter:
Adam Wiggins and Blake Mizerany present Sinatra and RestClient at RubyConf 2008. The talk details Sinatra’s underlying philosophy and reflects on using Sinatra to build real world applications.
Adam Keys and The Pragmatic Programmers have started a series of screencasts on Sinatra. The first two episodes cover creating a tiny web app and creating a REST service. $5 a pop.
You can also use rails as well, but that's a little overkill...
There are several layers involved when desiging a RESTful API, and at each layer there are several valid approaches.
TCPServer is indeed very low level, since you would have to implement the HTTP protocol yourself, which is not recommended.
One step up would be Rack, which takes care of all the low-level HTTP details. This is what all Ruby web frameworks like Rails, Sinatra or Ramaze use under the hood. It also assures that your application works on various application servers, like Passenger, Thin or Unicorn.
But even Rack is still low level, it gives you HTTP, but higher level frameworks take the boilerplate out of typical web programming. For an API you could look at a minimal framework like Sinatra, or a framework specifically designed for APIs like Grape or Rails::API. These will already assume a RESTful style API, so you should find them to be a natural fit.
Typical RESTful APIs are characterized by having resources identified by guessable (convention driven) URLs, and operations on those based on HTTP methods (verbs) like GET, POST, PUT, DELETE and PATCH. To truly embrace the spirit of REST as it was described by Roy Fielding however, you could move towards a more full "Hypermedia" API. The most visible difference is that responses are more self-contained. They are of well-defined media types (defined by yourself or by existing specs) containing links to related resources, rather than merely numerical ids. Similarly responses contain templates/forms describing the operations that can be performed. (There is more to it, but on the surface level that's what you will notice.)
This makes the API more discoverable, both by humans and machines, and it allows for a greater freedom in evolving the API. There could be a performance drawback, since a client typically would need to do more requests to achieve the same thing, but this can be prevented by well thought out design and caching. Garner is specifically made to provide easy server-side caching.
You could define your own media types that suit your application, commonly on top of JSON or XML, or you could look at existing specifications, notably Collection+JSON, HAL and JSON-API. It seems at the moment HAL has the biggest traction, with several libraries available on a variety of platforms.
There is seemingly not a whole lot happening around JSON-API, but two signifacnt projects, ActiveModel::Serializers and Ember-data, are both adopting (and at the same time, developing) this format, which means it could become a popular choice in the Ruby/Rails world.
Edit : typo
I'm using Sinatra too to develop simple REST solutions.
The thing is Sinatra is so flexible in many ways. You can build your project structure the way you like more. Usualy we have a lib/ tmp/ and public/ directories and a config.ru and app.rb files but as I sayd you can build whatever you want.
To remember is that Sinatra is not an usual MVC just because de M (model). For you to use sinatra for Simple CRUD web applications you need simply to load a gem.
require 'datamapper'
or other of your choice like sqlite, sequel, ActiveRecord, ...
and voilá you got a ORM under your Sinatra.
Under Sinatra you define routes that obey to four main proposes GET, PUT POST and DELETE.
require 'rubygems'
require 'sinatra'
get '/' do
erb :home
end
get '/API/*' do
api = params[:splat]
#command_test = api[0]
#command_helo = api[1]
#...
def do_things(with_it)
#...
end
#...
end
__END__
##home
helo
well you got the ideia :)
Finally. Learning Sinatra is not a waste of time because of it simplicity and because it gives (me) foundations of what web programming is.
I think In a near future it will be possible to "inject" Sinatra apps (Rack Apps) into a Rails3 project.
Take a look into github, there you will find many project built with Sinatra.
For further reading checkout Sinatra::Base.
For simple REST APIs I would also consider working directly against the Rack library (i.e. you may not need a framework like Sinatra). Routing for example can be quite easy for simple cases. I've put together a little example here: https://gist.github.com/4685445

Cappuccino, Django, AJAX, and fitting it all together - review my architecture!

I'm trying to get my head around Cappuccino. I'd like my StackOverview peers to review the architecture below and see if it makes sense - the aim is to utilize the unique benefits of Django and Cappuccino without doubling up where the technologies overlap...
When the web browser requests a 'friendly' URL (eg, /, /articles, etc):
DJango's urls.py matches this to a
view.
The view, rather than doing
DJangos typical work of filling in a
template with the locals dict,
returns the small 'stub' HTML used in
a Cappuccino app directly.
The client receives the Cappuccino HTML
The client requests the Objective J JS
URLs mentioned in the stub HTML
The end-user app is executed and
displayed in the browser
The browser now has a working app. When the user does something that
requests something from the server:
The browser sends an XMLHTTPRequest to a URL.
Django's URLs.py matches this to a
view.
The view does it work, perhaps interacting with the DB model. But instead of returning a template, Django returns some JSON.
The client recieves the JSON, and
does whatever it needs to do.
Does this make sense? We still have the benefit of friendly URLs, and the database being created for us to model our code. However rather than using templates, we're providing Cappuccino stub pages and JSON responses, in order to give users something more like a real app and less like an HTML templating engine.
Is there perhaps a better way of doing things? What do other Pythonistas use? Thanks for your feedback.
For a low traffic site, using Django's routing layer would be fine, but if you plan on getting a significant amount of traffic, you might consider having your proxying webserver handle the stubs.
As for the rest, it works and the TurboGears community has been doing it for years (I was a TG committer so that's what I normally use). The TG architecture of returning a dictionary to a template makes this trivial since you just set 'json' as your template engine.
Doing the same thing in Django isn't much more complicated. Just use the serialization tools to write the result to the response rather than using the templating calls.
Note that when you do an architecture like this, it's considerably easier to manage if you keep all the application logic in one place. Putting some app logic in Django and some in the browser causes things to start getting messy fairly quickly. If you treat your server as a dumb persistence layer (with the exception of validation/authentication/authorization), life is easier.
FWIW, I find Sproutcore to be easier to work with than Cappuccino if you're interested in heavier non-progressive enhancement frameworks.

Resources