📜 ⬆️ ⬇️

An evening with Sinatra to create a TwitterBar service

In general, I would like to introduce and tell a little about my little child, so to speak about the code in the evening. I have always believed and I think that if you want to learn something, and especially to understand technology, then of course you have to read a lot, and more importantly take, sit down and do this technology, even if just for fun. All the same, because programming is a creative work, and each of us has some ideas of projects, services, startups in our head, and even if not, there are still needs, some small ones, but if we take them and solve them this evening - this is the pleasure of learning. This is my course IMHO.

But somehow I had one desire, more precisely the need for twitter on “exhibitionism” in a broad sense. I regularly conduct my twitter where I regularly share links about technology, programming, sometimes good music, sometimes I just talk about life in Asia or where we travel there. So sometimes, I want these tweets to be visible to more people and by analogy with, for example, Last.fm which gives you the opportunity to show that you are listening to the current moment (by the way, I did the LastFM.bar service for this) I decided that it was good so that, for example, visitors to the forum in which I write, see my last tweet in the signature. The problem is that the forum is not mine, and you can only insert images into the signature, for example, no dynamics on JS and so on, only BBCode, only pictures.
So I decided that it would be great to put together a very easy and simple service that would do 3 things in all:
1. take the last user's tweet, for example in JSON format
2. parse this JSON, take the thematic picture for the background, adjust the fonts, sizes, arrange hyphenation in the text and draw this very text on the picture
3. give caching headers and give the picture itself
Everything.

Well, since lately I’ve been trying to do more and more projects on Ruby, in particular Ruby on Rails, but in this case I think that for me this big framework would be redundant. The good old Sinatra immediately came to mind. He can be called the progenitor of web frameworks, he was able to give life to such PHP followers as Slim, Fat3, Perl has his youngest to take the Dancer, and even took Mojolicious :: Lite much into his piggy bank. But all these frameworks are just a shadow, they have their own and slightly ugly DSL, there is no Ruby beauty, I’ll try to show you this beauty a little.
')
Let's start with a demonstration, since the project does not use the Database and is not commercial, in such options there is an excellent hosting service Heroku.com I used it, especially since hosting it was not as simple as Heroku did. And so, the demo is here: twitterbar.heroku.com
And the source can be downloaded directly from here, they are very few and they are very simple github.com/mpakus/twitterbar

Let's talk a little about Sinatra as a whole and go over the structure and source code of the application.

What is Sinatra? Actually, this is a regular gem (library) that can be put on one line.
> gem install sinatra

create new file
> mcedit first_app.rb

write in it
require 'sinatra' get '/' do "Hello World" end 


and run this file in the console
> ruby ​​first_app.rb
then a web server will be created on the local host on port 4567, now you can open your favorite browser and type localhost: 4567 in it and see the work of your first application on Sinatra.
Voila, easy and convenient!

What is the salt? In simplicity, they hooked up one library through require, painted the necessary routes through convenient DSL, took our favorite templating engine, for example, built-in ERB or HAML, someone and Slim already fell in love, brought daddy to us, for example, views templates, connected them and showed static files from the public folder, and you can even store templates directly in the main file, even simpler and more compact. All this is so flexible and customizable that you wonder how bright and understandable it is from the documentation www.sinatrarb.com/documentation

Now about my simple application for the evening.

At the root, there is the main application file index.rb and there are two helper classes whose methods I made singlet since I don't need objects, and even in Ruby, we have classes of objects :) it's hard to understand, but I thought something like that I saw in Basic language, execution right by code, line by line. But I was distracted, and so, two classes that I wrote and brought classes to my daddy: twitter.rb - which simply takes the last tweet of the user in JSON format and turns it into a regular ruby ​​hash
imagebar.rb - just a simple class for drawing on the picture of our text, uses the rmagick library, it is an adapter to the ImageMagick utility

And now let's go through the application and I will try to paint each line with a comment, by the way, comments like Ruby start with # I, for example, after so many years Perl was generally pleasant and comfortable.

And so index.rb in rows to understand what we use, for what and how.

 require 'rubygems' #  1.9 Ruby   ,    require 'sinatra' #    require 'sinatra/reloader' #          require Dir.pwd + '/classes/twitter.rb' #        require Dir.pwd + '/classes/imagebar.rb' #        require 'ostruct' #    yaml    ruby require 'yaml' #   yaml  set :env, :production #    configure do #  ,     set :root, File.dirname(__FILE__) enable :static #        publc enable :logging #  enable :dump_errors #    disable :sessions #       end get '/' do #       response['Cache-Control'] = "public, max-age=#{5*60*10}" #     erb :index #      views/index.html.erb   layout end #        get '/twit/:theme/:user.gif' do #  ,     theme_dir = Dir.pwd + '/themes/' #      user_name = params[:user] #       theme = params[:theme] #         #    ,      -  halt [ 404, "Page not found" ] unless user_name halt [ 500, "Sorry wrong theme" ] unless theme halt [ 404, "Can't find themes file" ] unless FileTest.exists? theme_dir + theme + '.yml' halt [ 404, "Can not found background" ] unless FileTest.exists? theme_dir + theme + '.gif' #  yaml       ruby  conf = OpenStruct.new( YAML.load_file theme_dir + theme + '.yml' ) #      twit = Twitter.get_last_post user_name #     ,   2  response['Cache-Control'] = "public, max-age=#{60*2}" content_type 'image/gif' #  mime  ,    ImageBar.draw theme_dir, theme, twit, conf #         end 


Just yes? And note, it reads like ordinary English-language and almost instinctively code.

Let's go further? Our two classes, the first is Twitter:
 class Twitter #    require 'open-uri' #     , - CURL  require 'json' #     JSON  class << self #           last_post = nil #         def get_last_post user_name #      download user_name #     get_data user_name #        end protected #    ,    def download user_name #     json   @last_post = open("http://api.twitter.com/1/statuses/user_timeline/#{user_name}.json").read end def get_data user_name JSON.parse @last_post #   JSON     end end end 

Just because you agree?

Well, our second class is ImageBar for drawing a tweet in the picture:
 class ImageBar #    require 'RMagick' #       class << self #     def draw theme_dir, theme, twit, conf #        #       img = Magick::ImageList.new theme_dir + theme + '.gif' text = Magick::Draw.new #      text.font = conf.font #     text.pointsize = conf.font_size.to_i #   text.gravity = Magick::NorthWestGravity #      text.fill = conf.color #   text.kerning = conf.kerning #   text.interline_spacing = conf.interline_spacing #   #   ,      wrap_text    text.annotate img, conf.width, conf.height, conf.left, conf.top, wrap_text( twit[0]['text'], conf.chars_in_row ) img.to_blob #      end def wrap_text(txt, col = 30) #       txt.gsub(/(.{1,#{col}})( +|$\n?)|(.{1,#{col}})/, "\\1\\3\n") end end end 

That's all, no more magic, everything is simple, like a brick and works as reliably and simply.

Taking into account the whole study of every mana of RMagick, for example, and Sinatra received a lot of pleasure and knowledge during the evening, and it is very important to keep our brains in good shape and not drown in this PHP monotony.

Now I’m happy to read a Sinatra book called Sinatra Up and Running - an accessible and easy-to-learn literature, tells all the subtleties of this simple, but at the same time very powerful and concise Ruby framework, I recommend both the book and the framework, since the world of Ruby is alive not only the Ruby on Rails framework, but also such very convenient horses, which in some cases are even better to use on tasks when not needed in a large Rails infrastructure, like creating any API, quick statistics collection, drawing some kind of static ones kart nok (counters, ratings, voting is), in general, all that requires simplicity, speed, and minimalism code loadable and overheads.

That's all, thank you all. If you have any questions, suggestions or comments, you are happy to read them and discuss them.

Source: https://habr.com/ru/post/143443/


All Articles