A391f932c5bb61131c99f8543a07f697

Hi, I have assembled some XML reading and encoding converting function, the encoded XML file is then saved as a Paperclip attachment.
Any idead how to write this code less ugly ?

def update_xml
    require 'rubygems'
    require 'rchardet'
    @shop = Shop.find(params[:id])
    url = "http://#{@shop.domain}#{@shop.xml_url}"
    tmp_file = "#{RAILS_ROOT}/tmp/#{@shop.id.to_s}_ceneo.xml"
    File.open(tmp_file,'w') do |f|
      data = ""
      data_sample = ""
      open(url) {|u| 
        u.each_line {|line| 
          data << line
          if data.size < 5000
            data_sample << line
          end
        } 
      }
      cd = CharDet.detect(data_sample)
      enc = cd['encoding']
      translate = Iconv.new("UTF-8//IGNORE", enc)
      data_translated = translate.iconv(data)
      f.write(data_translated)
    end
    File.open(tmp_file, 'r') do |f|
      @shop.ceneo_xml = f
      @shop.save!
    end
  end

Refactorings

No refactoring yet !

F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

July 28, 2009, July 28, 2009 21:39, permalink

No rating. Login to rate!

Tonsss of ways to refactor that.. methods should not be that large either (generally) since you are doing quite a few different things

A391f932c5bb61131c99f8543a07f697

astropanic

July 29, 2009, July 29, 2009 09:53, permalink

1 rating. Login to rate!

I have divided the method into smaller ones, and moved it into the model.

Any other ideas how to improve the code ?

class Shop < ActiveRecord::Base
  has_attached_file :ceneo_xml
  has_attached_file :logo,
  :styles => {
    :thumb => "75x110>",
    :product => "250x400#",
    :lightbox => "800x600>" }
  belongs_to :user
  has_many :assortments
  has_many :products, :through => :assortments
  has_many :shop_categories
  
  def update_xml
    data = fetch_xml("http://#{domain}#{xml_url}")
    data_utf8 = to_utf8(data,2000)
    save_as_ceneo_xml(data_utf8)
  end
  
  private
  
  def tmp_file 
    "#{RAILS_ROOT}/tmp/#{id.to_s}.shop"
  end


  def fetch_xml url
    data = ""
    open(url) do |f|
      f.each_line do |line|
        data << line
        logger.debug(".")
      end
    end
    return data
  end
  
  def to_utf8 data, size = 1000
    require 'rubygems'
    require 'rchardet'
    cd = CharDet.detect(data.first(size))
    enc = cd['encoding']
    translator = Iconv.new("UTF-8//IGNORE", enc)
    data_utf8 = translator.iconv(data)
  end
  
  def save_as_ceneo_xml data
    File.open(tmp_file,'w') do |f|
      f.write(data)
    end
    
    File.open(tmp_file,'r') do |f|
      ceneo_xml = f
      save!
    end
  end
end

Your refactoring





Format Copy from initial code

or Cancel