DEV Community

Cover image for How Do You Pass a Method to gsub in Ruby?
tiff
tiff

Posted on

How Do You Pass a Method to gsub in Ruby?

I am building off of Ben's static site generator, and I wanted to DRY it up a bit.

I have a few methods:

prod_build = ARGV[0] = "production_build"

# Read files

def page_partials(new_page_partial)
  pages = "site/#{page_partial}.html"
  new_page_partial = File.open(pages).read
end

def script_partials(new_script_partial)
  scripts = "site/#{script_partial}.js"
  new_script_partial = File.open(scripts).read
end

def style_partial(new_style_partial)
  styles = "site/#{style_partial}.css"
  new_style_partial(styles).read
end

puts page_partials()
Enter fullscreen mode Exit fullscreen mode

I'm not a Rubyist, though I've dabbled in it. I assume these methods are correct, considering:

build_string = base_html
  # How do you use a block in a .gsub method???
  .gsub("{{ head }}" {page_partials})
  .gsub("{{ seo }}", seo_html)
  .gsub("{{ main }}", main_css)
  .gsub("{{ dev }}", dev_html)
Enter fullscreen mode Exit fullscreen mode

I have a bunch of .gsub methods that expect a file, will change the file name, and in the build string, will create the file.

What I want to know is, as a JavaScript dev, how to pass these methods as parameters to the .gsub method in a block and if you can do this.

Shifting paradigms

I haven't looked at this code in a month as I was sick for that long. I have no idea what I was aiming for as such I am a little lost. JavaScript handles things much differently and I am trying to apply my js knowledge to Ruby and that seems to be a bad idea.

Thanks for helping, if you can.

Top comments (3)

Collapse
 
jonathanyeong profile image
Jonathan Yeong • Edited

Hey Tiffany! If I understand your question correctly, you're trying to call page_partials and substitute the text {{ head }} with the value of page_partials.

If that's the case. You should be able to call that method directly in the gsub. Like so:

# Where new_page_partial is the file name of whatever page partial you want to pass in.
base_html.gsub("{{ head }}", page_partials(new_page_partial))
Enter fullscreen mode Exit fullscreen mode

It does look like your page_partials function might have a small bug. Here are my comments for it:

def page_partials(new_page_partial)
  # bug: page_partial isn't being referenced anywhere. You may want to use new_page_partial instead.
  pages = "site/#{page_partial}.html"
  new_page_partial = File.open(pages).read
end
Enter fullscreen mode Exit fullscreen mode

Hopefully this helps! I'm happy to pair on any Ruby code!

Collapse
 
tifflabs profile image
tiff

Hey! Yeah we should definitely link up as I'm struggling with it a bit. It's pretty late on the East Coast, but I'll DM you on Twitter tomorrow if that's okay?

Collapse
 
jonathanyeong profile image
Jonathan Yeong

Yeah for sure!