Forum: Ruby Parsing JSP files and adding a Line

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Donald D. (Guest)
on 2006-03-20 20:20
Basically, I'm still pretty much freshmeat when it comes to Ruby, but
I'm intrigued by the language and wanted to start playing around w/ it
for the J2EE project that I'm on.

I wrote some Ruby Code that would find all the jsp's in our project
(around 200) and look for a XML-Tag and after this tag it would insert a
new line w/ another tag... Some basic scripting. But I doubt I'm doing
it the most efficient way.

Another problem I have is if within the original JSP file, a Tag carries
over onto the next line. I would ideally like to find a Xml-Tag and
insert another block after the end of it. What would be the best way of
doing so? Thanks.

Here's the relevant code:

def insertStr(fname, str, regexpr, isHeader)
  notAdded = true
  File.open(fname, 'r+') do |f|     # open file for update
    lines = f.readlines             # read into array of lines
    lines.each do |line|            # modify lines
      if notAdded
          if line =~ regexpr        # If the tag is found
            if isHeader               # insert include string
              line << str + "\n"
            else
              line.replace(str + "\n" + line)
            end
            notAdded = false        # make sure nothing else can be
inserted
          end
      end

    end
    f.pos = 0                         # back to start
    f.print lines                     # write out modified lines
    f.truncate(f.pos)                 # truncate to new length
  end                               # file is automatically closed
  return !notAdded
end
Guest (Guest)
on 2006-03-21 17:34
A Xml-Parser might be able to help?

donald dapp wrote:
> Another problem I have is if within the original JSP file, a Tag carries
> over onto the next line. I would ideally like to find a Xml-Tag and
> insert another block after the end of it. What would be the best way of
> doing so? Thanks.
This topic is locked and can not be replied to.