Showing posts with label serializer. Show all posts
Showing posts with label serializer. Show all posts

Friday, December 9, 2011

Serialize and deserialize object in ruby

Hello Rubies,
          Want to serialize and deserialize the ruby object? than use the inbuilt method of ruby.

Assume have the field says 'content' as text field of xyz table and it stores the value in serialize hash format but when we do the sql query to retrieve content than it gives output as normal string format.

content has value:
---
ruby:
  :value: 50
  :label: "ruby %"
java:
  :value: 30
  :label: "java %"
c:
  :value: 50
  :label: "c %"

Lets trying to get the content value by raw sql statement like "select content from xyz" than it return text (string) object.

now we load the object in serialize form by
puts YAML::load(content)
visa versa we have string and set to serialize object than need to use  
puts YAML::dump(content)
Same way around if you have deserialize content and want the serialize form then use content.to_yaml. It gives result in serialized form.

Friday, September 2, 2011

Generate .xlsx file in ruby using simplexls

Hello Rubies,
          Generate simple .xlsx file using spreadsheet cause the problem it shows extension as .xlsx but it actually .xls file itself.
          So, now we required better option to generate .xlsx file in ruby by using simple_xlsx_writer gem.

First of all we require to install simple_xlsx_writer by using
  sudo gem install simple_xlsx_writer
 
Lets generate example.xlsx

require 'simple_xlsx'

def generate_xlsx
   dummy_data = [
     ["Jyoti", "1960-07-27", "http://priyankapathak.wordpress.com"]
     , ["Ramesh", "1956-06-20", "http://twitter.com/pathakpriyanka"]] 
   file_name = "#{RAILS_ROOT}/tmp/example.xlsx"

   serializer = SimpleXlsx::Serializer.new(file_name) do |doc|   
      doc.add_sheet("Testsheet") do |sheet|
         sheet.add_row(["Name", "Birth Date", "URL"])
         dummy_data.each do |data|
             sheet.add_row[data[0], 
                 Date.parse(data[1]), '=HYPERLINK("'+data[2]+'","Hit me")'
         end
      end 
   end
   send_file file_name
end

This code helps you to generate simple .xlsx file. Want more information than simply follow http://rubydoc.info/gems/simple_xlsx_writer
Hope this post help you. If have any query or suggestion than post a comment.