What Windows 8 could have been

15th December 2012 at 15:15

This post was supposed to be yet another Windows 8 review but, as I’ve gained experience with the latest Microsoft OS, I saw the potential for something a little more interesting. I’ve been using Windows 8 as the only OS in my main computer since it was officially released by Microsoft, so I might say I have some experience, now, to tell you a thing or two about it that you probably missed in other reviews. I’ve already used Windows, Mac and Linux as my primary OS (and I tend to change it quite frequently), and I find advantages and disadvantages in all of them. I’m pretty “agnostic” in most technology debates, and OSs aren’t an exception, so these thoughts aren’t distorted by fanboy opinions. I didn’t do a simple review not only because the Internet is full of it (really, I’m not even posting any links), but because my continuous usage of this new OS kept bugging me more and more about very specific details. So I’ll skip the typical suspense and just tell you my quick opinion about it, so I can discuss what I see as the most pressing issue: what Windows 8 could have been.

Firstly, I know many people don’t agree with me, but I actually think Microsoft changed the game with Windows 8 and the Surface. The notion of converging the laptop and tablet experience seems almost intuitive to me. As you might already know, tablets are the latest revolution in computing and are slowly throwing laptops to oblivion as once laptops did to desktop PCs (OK, I know it’s not that simple, but when we look at market shares there’s no doubt the landscape is changing). Tablets are also more portable than the thinnest ultrabooks, have a more intuitive and friendly input, don’t have the dreaded noisy fans, have better communication options and so on (I could go on listing the advantages of tablets over any laptop, but I guess I made my point already). So isn’t it silly that we’re still using them just as consumption devices (read: overpriced toys)? Is the great revolution in computing really only worth it for browsing Facebook and throwing some birds at evil pigs?

The answer, of course, is no. If these devices are so much better than their ancestors, then we must be able to switch and leave the old laptops behind. Some power users might not be able to do it, but that’s exactly what happened in the transition from desktop PCs to laptops anyway. Apple has been very careful in this matter: they have slowly improved iOS to meet more demands and updated Mac OS to be more iOS-like. They’re basically doing baby steps for converging the two OSs, cautious not to make a very risky move. I’m still very curious about what the conclusion of that convergence might look like. Microsoft, on the other hand, went all-in about the matter and evolved from a pure PC OS to a completely hybrid, both tablet-friendly and “traditional”.

In my opinion, and this might be controversial, Microsoft decided, for a change, to be the innovator and to push to the market a concept that is probably ahead of its time. They were so proud of their concept, they even build their own tablet/laptop hybrid just so they could show the full picture of their envisioned game changer product. This move is as refreshing as it is unexpected. So, as you can see by now, Windows 8 and the tablet/laptop hybrids approach have really caught my eye and promise to be a welcome revolution brought by an unexpected player.

So… what could possibly go wrong? Here are some of the details I’ve been struggling with lately.

Affordances

In interaction design, affordance is the quality of an element to display to a user how it is supposed to be used. Imagine a door with no signs and with equal handles on both sides. That’s an example of poor affordance, since you don’t know if you’re supposed to push it or pull it. A door with better affordance would have the handle only in the side where you needed to pull and probably a sign in each side displaying the correct action.

The Modern UI design aka Windows Store design aka Metro style design is, in my opinion, a nice UI that makes Windows Phone 7 and 8 look much more fresh and lively than the big guys iOS and Android. However, I’m not so sure about it in tablets and specially on regular PCs. One of its major advantages, the flat UI that strips down the unnecessary and focuses on content, is also one of its major flaws, because you’re also losing some important elements that weren’t just there for decoration. Don’t agree?

This image is showing two different elements from the same screen (not in their actual position, just next to each other in this picture for comparison). The one on the top is just a title with no action on click, and the one in the bottom is a button to a settings page (although we’re already in a settings panel, and another button in the same panel already points us to the Control Panel, another settings tool).

I could add more examples, but I hope you got the idea. Cleaning the UI is a very good idea, but you must do it with caution. “Make it as simple as possible, but not simpler”.

The best of two worlds?

One of Windows 8′s most ambitious promises is the convergence of desktop and tablet experiences. As I said, I’m a big fan of that concept and I believe that’s a trend to follow. But a concept is one thing, execution is another. My ideal use case would be something like:

I pick my tablet for working on the go. Since I don’t have paperwork nor a cumbersome laptop to carry, travelling with everything I need for work (just a tablet) is easier than ever. In those free times I can just turn on my tablet and browse my favourite websites, check my email and so on. When I get to my office I just link the Bluetooth keyboard and mouse and the HDMI display, start the traditional environment and fire up the MS Office suite, the IDE, etc.

Next day I decide to do some work at a coffee shop, so I just bring the tablet and a keyboard (a Surface keyboard would add no bulk to the pack, and a keyboard dock like what we see in Asus’s offerings would, in a worst case scenario, make me feel like I’m carrying a thin netbook).

When going to meetings, presentations or others I simply carry the tablet and use it with the onscreen keyboard, since I won’t be typing long sequences of text. In between, I think about my laptop and wonder when was the last time I used that heavy, noisy and awkward machine.

This use case is what I think when I see new hybrids in the market running full-blown OSs in a tablet form and when I hear Microsoft state how Windows 8 promises to deliver the best of both worlds. Unfortunately, that’s not what’s happening.

Firstly, Windows RT, a dumbed-down version of Windows 8 developed to run on ARM processors, miserably fails to live up to that promise, as you won’t be able to run legacy apps in it (read: you can’t install typical desktop applications, like the ones you absolutely must have for your job).

Also, when using a tablet with no mouse or keyboard, this ideal vision means not interacting with the traditional desktop and its windows, as they’re not the most touch friendly interfaces you’ll see. So it’s too bad that actions such as file management and configuring some settings have to be done in the desktop environment. I can’t help but think that Microsoft’s tight schedule for Windows 8 left many holes in the OS, and this lack of support for the continuous use of the tablet environment shows many of them.

These holes in the OS aren’t an exclusive of the tablet interface. As an example, in the desktop mode hitting the Networks taskbar icon brings a panel in line with the new design, but hitting the Sound or Power taskbar icons still brings the old style popup. Also, when using the desktop environment, the Charms bar has close to no functionality (but it still shows up when hitting non-configurable hot corners). There are many more rough corners that still need to be polished if this is to look like a finished product.

Finally, the integration of these two poorly-implemented worlds is nothing but disappointment. If you like a Metro application, you can’t run it as a window in the desktop environment (nor can you go full-screen in most desktop applications). If you open a file in one of the environments, the only way to move it to the other environment is to open it again manually using another application. The only way to see two Metro apps at once (or any Metro app while using the desktop interface) is by snapping one of them to the left or right of the screen. However, you have no control of the size of each app, and you can’t have two documents side by side, since the distributed space isn’t 50%-50%, but more like 75%-25%.

Apps, apps, apps

At the end of the day, what really matters is the applications. That’s why most users prefer Mac OS or Linux over Windows, but when you look at market shares that’s not what it looks like. However, with this new OS Microsoft seems to be trying to get rid of its huge market advantage.

As I’ve stated before, there’s not much integration between the two different environments of Windows 8. So, while you have a huge collection of legacy apps in the traditional one, you’ll feel the emptiness of options in the newest one. If desktop apps could integrate with the tablet mode this wouldn’t be such a big issue, because we’d have something to cover that emptiness while the new apps ecosystem was being developed. But we don’t, so if you’re like me you’ll probably want to make use of that awesome new environment, but will find no reason for it and eventually give up.

Things get pretty ugly if you consider Windows RT instead of 8, because it also has a desktop mode but lacks the support for legacy apps. So yes, the market leader that has built its success on top of its huge apps ecosystem has just started a new one from scratch and one of the versions of its newest OS doesn’t even support the old one.

Also, if this new desktop/tablet mix in the same OS serves as a “bridge” from the old ecosystem to the new, I can’t figure a simple reason for Microsoft to launch the Surface with RT before launching the Surface with 8. They basically launched a device with virtually no ecosystem and waited to later launch a similar device with support for all Windows applications. That’s like trying to build a whole village in a desert island and only later building a bridge to it. I wonder how much has Microsoft lost with this new, unpopulated village already.

Finally, if we look to the Metro apps that come with the OS, there’s also some aspects that make me think this could have gone a totally different way. The built-in calendar app couldn’t import all calendars from my Google account (in fact, it could only import the personal one), so it’s useless for me. The messaging app can’t send new messages if I’m set as invisible, and can’t get them from contacts that show up as offline, so this one’s also useless for me. Thanks to the poor integration between the two environments, I can’t get a mini player of the XBox Music app (only a snapped panel from top to bottom that shrinks my horizontal desktop area). These are just some examples of the poor job that leave us early adopters with little incentive to keep trying the new environment.

To sum up

Please don’t get me wrong: I love Windows 8′s concept and I share (more or less) Microsoft’s vision for the future of computers. If this was the typical review, I’d spend more time highlighting some good implementations and how I believe it’s the right direction. I might even have recommended the upgrade. However, my goal is to highlight what I find poorly implemented in such a great concept.

Thanks to this whole notebook/tablet hybrid concept, I’ve started to look at the latest ultrabooks as kind of obsolete devices. They don’t have touch screens, it’s impossible to use them while walking without looking awkward, and so forth. The same goes for all Apple’s notebook options (that’s probably the reason why most Apple fans don’t agree with this vision). However, after quite some time with Windows 8, I fear we don’t have a strong alternative yet.  Yes, this is definitely an important step in that direction, but it’s still looking too immature, for now. Windows 8 seems to have suffered a lot from its tight schedule and, thanks to this incomplete effort, we now have a vision of what’s to come, but are left with a poor demo of it.

All in all, this could have been a new revolution in the way we use our computers. As it stands, it’s nothing but a glimpse of what that revolution might look like. Maybe they’ll get it right in an hypothetical Windows 9. After all, Microsoft is known for releasing great versions of Windows after disappointing ones, and disappointing versions after great ones (and so far, this pattern seems unchanged). Or maybe Apple will get it right first.

Limpar a feed do Facebook e outras histórias do Sapo Codebits VI

27th November 2012 at 21:00

Decorreu de 15 a 17 de Novembro a sexta edição do Sapo Codebits, um dos eventos de tecnologia mais populares do país. Foi um evento tão imersivo que só passado este tempo é que arranjei tempo no meio de tanto trabalho que atrasou para poder escrever alguma coisa sobre o assunto. Para quem não conhece, o Sapo Codebits é um evento de e para programadores, engenheiros informáticos ou electrotécnicos, ou aficionados de tecnologia no geral. Nesse evento incluem-se actividades como palestras, workshops, exposições de tecnologia e vários concursos, com especial destaque para o já famoso concurso de 48 horas seguidas de programação. Para mais detalhes sobre o evento no geral, fica o link para a apreciação que fiz após a edição do ano passado.

Este ano contou com algumas novidades interessantes, como os workshops de hardware (onde deu para fazer um test-drive ao famoso Raspberry Pi e falar com o Rob Bishop), a restauração de máquinas de arcade antigas (incluindo projectos interessantes como usar uma máquina de Sega Rally para controlar um carro telecomandado), entre outras. De negativo, foi especialmente a maior escassez de comida (incluindo o desaparecimento do Red Bull a meio do evento, quando as horas de sono em falta mais o exigiam).

Tal como aconteceu no ano passado, houve talks de grande qualidade e tenho pena de não ter assistido a mais. Felizmente, os vídeos foram disponibilizados pela Sapo, e ainda não consegui acabar de ver todos os que queria. Recomendo especialmente os vídeos da talk do Miguel Gonçalves intitulada “Move fast and break things“, do Rob Bishop a falar do Raspberry Pi em “Raspberry Pi: past, present & future” e ainda o “The art of readable code” do Pedro Morais.

Desta vez o projecto que desenvolvi, intitulado Facebook Decrapifier, foi uma extensão para o Google Chrome que esconde posts sobre assuntos que não queremos ver (política, futebol, música pimba, etc.) e evita ainda o chamado Facebook jacking (apenas a parte de escrever posts de conteúdo duvidoso). Mesmo não tendo ganho nenhum prémio, o grupo teve uma excelente prestação no concurso. Fica o link para o vídeo oficial que foi mostrado durante o pitch final.

Tal como aconteceu no ano passado, participar neste evento foi uma experiência muito gratificante para quem está dentro da área e gosta do que faz. Uma vez mais digo que deu para adicionar novas competências ao currículo que o curso que estou a tirar não consegue, por si só, dar, o que só por si já faz tudo isto valer a pena. Tenho pena de não saber onde vou estar para o ano, já que por essa altura já terei acabado o curso, e por isso não consigo saber ainda se estou disponível para participar na próxima edição (a vontade de lá voltar nem se questiona).

Para o próximo ano, segundo foi anunciado pela PT, o Codebits vai ocorrer em simultâneo em Portugal e também no Brasil. É mais uma evidência do crescimento que este evento está a ter, fruto da sua excelente organização e conceito. Tal como referi há um ano, é sem dúvida uma experiência que recomendo todos da área a procurarem.

Avoiding the “think outside the box” trap

25th October 2012 at 20:03

These days I’m getting sick and tired of all the “think outside the box” talk. In my area (technology and computers stuff) we have three kinds of young people: those who have yet to wake up for reality (mostly gamers that chose this area because it’s about those machines that can run videogames); those who want to play safe and spend their years being treated as slaves in a low-wage and unfulfilling job; and those that love to “think outside the box”. So what is that thoughtful activity anyway?

“Thinking outside the box” means trying unconventional ideas and questioning the status quo to get to new conclusions and possibilities. Imagine all you take for granted in this world and all your beliefs being put in a box. That means that whenever you’re solving a problem or looking for an answer, you’re thinking inside that box of yours. You’re in your comfort zone. You’re safe. But there is a full world of possibilities outside of that box to be explored, and sometimes the answer to a problem might just be hidden outside of those boundaries. So you have to step out of your comfort zone and explore new ideas and beliefs you you want to get your answers.

That is the theory. Now for reality.

At least among rather young people (18 to 30?) in the technology area, that expression is very popular. People use it to try to stand out from the crowd, although much of the crowd is using it already by now. Even though they might not notice it, they’re not really using it in its original meaning anymore: for the tech guys, “thinking outside the box” is avoiding the low-wage unfulfilling job and challenging the standard, usually by trying to live an entrepreneur’s adventure or simply by chatting about the latest innovations and what cool technological projects could be made out of them. In every meetup, in every talk, in every event, there it is: the dreaded “think outside the box” telling you to create the next Google or Facebook and live the startup entrepreneur’s dream (this is actually an oversimplification, but I hope you can still see my point here).

So, have you noticed something terribly wrong so far? If not, please read the description of the original meaning of that expression again. It seems that almost all the tech guys are pointing to the same direction when they talk about “thinking outside the box”. Not just to the same direction, but many times also to the very same spot! Now how’s that for challenging your beliefs, getting out of the comfort zone and exploring new ideas and possibilities? How come can you talk about shifting the way you question the world and then fall to the same exact spot as everybody else who tries to do the same?

Eager to stand out from the crowd and expand their ideas, people move their thoughts out of their box, just to let them fall in another one. This “second box”, as it might be called, is just a trap state where you can easily fall if you don’t see it. But hey, nobody said it’d be easy to truly get out of that hated box! The whole purpose was to do the near-impossible and change the status quo, so it shouldn’t be too much of a surprise if there are some traps and pitfalls on the way.

So how can that trap be avoided so that we can truly achieve great paradigm shifts and new discoveries? Unfortunately, there is no right answer for it, at least that I’m aware of. If I new it, I’m sure I’d be a much better and happier person by now. However, I’m sure it wouldn’t hurt to stop thinking so much about creating new startups and launching new technological products, and start trying to push creativity and imagination to come up with amazing new ideas. Not million-dollar business ideas (although those might also be welcome), but simply crazy ideas that at the end of the day will have an impact on you and on the world around you.

How many tech folks would consider travelling to a country not knowing a single word of their language just to help children with family problems? How many with the right skills would work with a young NGO to develop their website without asking anything in return? And how many would spend hours every week watching recorded lectures online from the world’s best universities and doing their exercises?

As every other guy will tell you, it’s still nice to look for entrepreneurship adventures, though (as I’ve also done and intend to keep doing). Just keep in mind that it’s just one pattern you can follow when you’re trying to think different and broaden your scope of the world, and that there is an endless list of other patterns, some of them better, others worse. Just don’t fall in the trap of immediately going for that “second box” if that wasn’t your initial goal.

If you dodge that trap, there is a whole world of new adventures waiting for you. A scary world, way different from your usual assumptions and mostly unknown  And still, powerful enough to amaze you and to give you new insights and tools for critical thinking, problem solving and self-fulfilment.

How to keep your blog’s visitors flow without even trying (bonus: many unrelated stuff)

20th June 2012 at 11:28

Those who explore this blog a little further than the first post that came up in the Google search may notice that I haven’t posted any new content since the end of January. That’s almost five months ago! It isn’t because I lost interest or run out of content to share. It’s just because recently my Master’s degree has pulled a lot of time and effort from me and I just hadn’t got the chance to update my blog as I’d want to. I would, occasionally, check its visitors statistics, and what I found time after time (including now) was that, despite the lack of new content, visitor rates just wouldn’t decrease. In fact, I believe they’re now higher than by the time I shared my latest post back in January.

But how is it really possible to sustain or even increase a blog’s visitor flow by simply not posting any new content? Isn’t that a somewhat counter-intuitive move that should stop your blog’s momentum and drive it to oblivion?

It probably is. But, as you may have read in many other places, it all comes down to one thing: timeless content.

Provide valuable content, and people will read it and share it. You can put a lot of effort in techniques such as SEO or social engagement, but at the end of the day if your content is meaningless it won’t help people and they won’t come back. And if you want to rely on your content to sustain visitors flow even when you’re away for a long time, then it must be timeless. If I kept posting specific news of things that only mattered in that week (like I did, sometimes) this blog would be dead by now, because that’s very momentary content that, as useful and valuable as it might be, will fade away very quickly and will need new content after that to keep the blog’s momentum. If, however, you post content that will still be valuable months (or even years) after, then new visitors will still come by even after a long time.

So does all this theory match with the real world?

Absolutely. My most successful content is the 2-part post about the impact of Facebook in society (part 1 and part 2, although you’ll need a translator if you don’t understand Portuguese). This isn’t any piece of news that would fade away quickly (in fact, it was posted more than a year ago and still gets more traffic than any other post). This was a careful analysis with many interesting insights and conclusions, valuable not only when it was posted, but also now and certainly in the future. Other great hits are my updated guide for the Semantic Web in Ruby on Rails (which might be very valuable for many years, as the best blog posts I could find before writing that one were from around 2008), my posts about fine-tuning Fedora 15 (both the initial post and the tutorial, timeless because they present a very pleasant alternative to other OSs, although new versions of Fedora are coming up) and also my detailed experience with free web hosts (it could probably benefit from an update, but is still valuable content today).

To sum up, if you want to be heard don’t just talk about the latest trend: create content that, even after months or years, still offers readers valuable information. If you do it, you’ll probably be able to slow down when other matters urge and still don’t feel any loss of momentum. This is, of course, a simple opinion of a casual blogger, based on low numbers statistics: my blog’s daily visitors are around just 20~30, which is great for a personal blog with 20 published posts but still too little to draw more conclusive results.

Bonus: many unrelated stuff

I’ve been away from my blog but I’ve still been publishing interesting content through social media. If you want to receive the latest updates, you can follow me in Twitter: @ricardoplopes. Here are some of the best links I’ve been sharing, just to make up from all the time I’ve spent without posting on this blog:

The Sex Scandal Technique: How to Achieve Any Goal, Instantly (and Party with Tim Ferriss)

Windows Desktop UI Concept

Why We Have to Go Back to a 40-Hour Work Week to Keep Our Sanity

Jennifer Pahlka: Coding a better government (TED talk)

How Linux is Built (Youtube video)

15 Things People Absolutely Hate About Your Website

Sheryl Sandberg’s Inspiring Speech At Harvard Business School

Developing for the Semantic Web with Ruby on Rails, the 2012 guide

30th January 2012 at 10:47

The Semantic Web, an Internet of of connected knowledge, meaningful data and machine-readable information, is seen as many as the future of the Internet. Envisioned by Tim Berners-Lee, its purpose is to transition from a web of unstructured documents into a “web of data”, in which we could browse and search for data not only based on syntactic  keywords, but also based on semantic meaning. However, it’s awkward to realise that most of the work around the Semantic Web is done in Java, and many technologies with great future potential, such as Ruby on Rails, are seemingly forgotten.

Having developed a Semantic Web project using that Ruby framework, I found very scattered information and tiny bits of contributions, many already obsolete. It’s almost shocking to see so few and old information around such a modern framework with such a vibrant and participating community developing for it. As such, having collected many of those bits of information, I believe it’s time to put them together and finally create an updated guide to the development for the Semantic Web with Ruby on Rails.

Disclaimer: This is not a step-by-step tutorial, so don’t expect to know how to develop a Semantic Web application in Ruby on Rails as soon as you finish reading this. The main goal of this article is to save hours of research and show the best and updated tools available. Also, the code examples aren’t necessarily complete or 100% correct, as their goal is to explain something, and not simply being copy+pasted to a tutorial application.

Building the ontology and fetching relevant data

If you’re going to develop a website using the concept of the Semantic Web, one of the first things you’ll need is an ontology. You may find many useful ontologies capable of describing the data your web application is going to use (the Swoogle project might be a good place to start your search), but you might as well have to develop your own. If you’re building your own ontology, I recommend using Protégé for it.

The development of the ontology is out of the scope of this article, as it has no relation to the platform used to develop the web application itself, so if you don’t know how to start I’d recommend reading some simpler guides first (here’s a short collection of links that might help you with that).

After you have the right ontology to power your web application, it’s time to to fetch the data.Unless you’re aiming for a very limited and controled set of elements, you’ll probably want to develop a screen scraper or use an external API. Using the Ruby gem Nokogiri, you can easily browse and fetch the information you want from any useful website. Here is a simple example of a screen scraper for your application:

items = []
doc = Nokogiri::HTML(open(website_url))
doc.css(".item").each do |item|
  link = item.at_css(".info h4 a")[:href]
  item_doc = Nokogiri::HTML(open(link))
  name = item_doc.at_css("h2#title a").content.to_s
  description = item_doc.at_css("p.description").content.to_s
  items << ["name" => name, "description" => description]
end
return items

As you see, this little example simply iterates through all the elements of the website of the class “item”, browses to their specific page and then extracts the name and description. This technique may have its flaws, like being vulnerable to major website redesigns, but it’s also a very simple and rapid way of extracting large quantities of information.

Ideally, you’ll want to save your new information in XML files or in a database, so you can use them later without having to run the fetcher again. This, of course, is just a temporary location, ready to change as soon as the Semantic Web enters the game.

Putting the Semantic Web in Ruby on Rails

It’s easy enough to develop for the Semantic Web in Java, as you can easily find a large set of tools to help you in every stage of the development. In Ruby it’s not that easy at all. After some research you’ll probably come across two Ruby gems that handle the semantic graph: ActiveRDF and RDF.rb. However, ActiveRDF is now outdated and it doesn’t seem to work as it should in Rails 3. So RDF.rb it is, then.

Now that we have the tool to manage the semantic data, we should save our raw data in a semantic graph. We’ll use the N-Triples format for that. First you’ll need to define all the semantic relations of your data:

include RDF
MyOnt = RDF::Vocabulary.new("http://ricardolopes.net/myont.owl#")
graph = RDF::Graph.new
items.each do |item|
  graph << [item["uri"], RDF.type, MyOnt.Item]
  graph << [item["uri"], MyOnt.hasName, item["name"]]
end
return graph

This example assumes that you have an ontology with the URI http://ricardolopes.net/myont.owl, which has at least a class Item and a property hasName. This example, as all others in this guide, is far from complete, as it is just used for quick demonstrations. One thing it doesn’t show is how to create the unique URI for each item. That is up to you to decide, as every project is different. However, when you have a unique identifier for every item, you probably should do something like item["uri"] = MyOnt[unique_identifier]. Beware, though, that if you use MyOnt to store individuals, you’ll no longer have an empty ontology serving only as a schema. You’ll probably find it more useful to use an URI for the ontology schema and another for the individuals (MyOnt and Data, for instance).

After that step, you’ll then need to store the information of the semantic graph you created in an N-Triples file:

RDF::Writer.open("data/graph.nt") do |writer|
  graph.each_statement do |stmt|
    writer << stmt
  end
end

This is it. you should now have a complete N-Triples file with all your semantic information. Now that you have the semantic data, you may start using its full potential.

Querying the graph

If you’re not new to the Semantic Web development you’re probably used to SPARQL when it comes to querying for information. In Ruby on Rails you’ll find it possible to do such queries using pure Ruby, thanks to the RDF.rb gem. Imagine you have the following information:

<http://ricardolopes.net/data/2011/01/10/ricardolopes>
<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>
<http://ricardolopes.net/myont.owl#Developer> .

<http://ricardolopes.net/data/2011/01/10/ricardolopes>
<http://ricardolopes.net/myont.owl#hasName>
"Ricardo Lopes" .

<http://ricardolopes.net/data/2012/01/30/semanticwebarticle>
<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>
<http://ricardolopes.net/myont.owl#Article> . 

<http://ricardolopes.net/data/2012/01/30/semanticwebarticle>
<http://ricardolopes.net/myont.owl#hasName>
"Semantic Web article" .

<http://ricardolopes.net/data/2011/01/10/ricardolopes>
<http://ricardolopes.net/myont.owl#isAuthorOf>
<http://ricardolopes.net/data/2011/01/30/semanticwebarticle> .

This means that we have an individual of the class Developer that has the name “Ricardo Lopes”, and an individual of the class Article that has the name “Semantic Web article”. We also have a relation that states that the Developer “Ricardo Lopes” is the author of the Article “Semantic Web article”.

Imagine now that you’re showing the article “Semantic Web article” and want to show the name of its author. Using the RDF.rb gem, you could do it simply using Ruby:

article_name = "Semantic Web article"
...
graph.query([nil, MyOnt.hasName, article_name]) do |stmt1|
  # stmt1.subject now holds the URI of the article
  graph.query([nil, MyOnt.isAuthorOf, stmt1.subject]) do |stmt2|
    # stmt2.subject now holds the URI of the author
    graph.query([stmt2.subject, MyOnt.hasName, nil]) do |stmt3|
      # stmt3.object now holds the name of the author
      author_name = stmt3.object.inspect
    end
  end
end

This is equivalent to the SPARQL query:

PREFIX MyOnt: <http://ricardolopes.net/myont.owl#>
SELECT ?author_name
WHERE {
  ?article MyOnt:hasName "Semantic Web article" .
  ?author MyOnt:isAuthorOf ?article .
  ?author MyOnt:hasName ?author_name .
}

If you still prefer to use SPARQL instead of pure Ruby, there’s a gem for that: SPARQL-Grammar. Beware, though, that, as I’ve said before, the Semantic Web in Ruby has still a long road to run to catch up with languages such as Java. The work to bring SPARQL to Ruby is still very incomplete and there are many things you can’t do (sometimes I couldn’t even define prefixes, which resulted in some very ugly queries). If you want to give that gem a try, your code should be somewhat similar to this:

queryable = RDF::Repository.load("data/graph.nt")
authors = []
query = # the SPARQL query above
sse = SPARQL::Grammar.parse(query)
results = sse.execute(queryable)
results.each do |result|
  author = result[:author_name].to_s
  authors << author unless authors.index(author)
end

You now have the tools you need to make full use of the semantic information of your application. With many Semantic Web applications, this is all you need to know. However, there’s more we can do. If you’re developing in Ruby on Rails, chances are you’re intending to put your web application on the cloud. And there’s also a good possibility that you may want to change some of your data in the future. That’s when a simple file is no longer an option to store your data and you must upgrade it to a Triple Store.

Leveling up to a Triple Store

A Triple Store stands for an N-Triples file as a database stands for an XML file (sort of). So if you’ll ever need to update the semantic information of your web application, that’s what you should use.

There are plenty of Triple Stores in Java for you to run locally or in your server, like Jena, AllegroGraph, Sesame and many more. There are interfaces that let your Ruby application interact with those Java Triple Stores, so if your server supports Java or localhost is as far as you’ll get, them one of those might be the right solution for you.

However, if you’re developing the webapp in Ruby on Rails, chances are you want it online and your server might not support other languages. If that’s the case, then you need to develop an interface that creates an abstraction in your server’s database so it acts as a Triple Store. Such an abstraction would probably use a single 3-column table (for subject, predicate and object) and would return a set of triples for every query received. The hardest step should be converting from SPARQL or pure-Ruby RDF.rb queries into the proper SQL query.

Fortunately, if you use PostgreSQL and/or SQLite, there’s an amazing work done that integrates those databases with RDF.rb data. It’s the Ruby gem RDF-do, and it may save you days of work and many frustrations.

To sum up

Once one grasps the power of the Semantic Web, it’s not easy to ignore its advantages and future potential. However, as you can now see, the work around it in Ruby feels scattered and incomplete. Because it was so difficult to come across these scattered pieces of great work and because of what can be achieved when they are all connected, there was a great need of putting all this knowledge together. Yes, there are other similar guides online, but many are so outdated that may put you on the wrong track.

As I’ve pointed out before, this wasn’t intended to be a step-by-step tutorial for you to copy+paste all the code you needed to develop a basic application. If this article is so long as it is, imagine how it would be with all that information. It’s more like an updated guide you can use to save hours of research and frustration.

As I’m fairly new in this area, there are probably many mistakes in this article. Still, I hope that the bundled information can make up for that.