First of all I've never used ruby and capifony so this question might be very easy for some of you but not for me. I tried to find examples related to my question but couldn't find any or I'm too new to ruby to miss!
When deploying my Symfony app, the value of a particular key in my parameters file should be dynamically appended so, rather than using exact generic value coming from distribution file below:
parameters_prod.yml.dist
parameters:
my_prefix: my_value_prefix_
Straight after deployment, parameters.yml should read like below:
parameters.yml
parameters:
my_prefix: my_value_prefix_8235647895
8235647895 part above is going to be timestamp.
How can I do this?
My current deploy.rb
namespace :mytest do
desc "Upload the parameters.yml"
task :upload_parameters do
origin_file = parameters_dir + "/" + parameters_file if parameters_dir && parameters_file
origin_file_append = parameters_dir + "/" + parameters_file_append if parameters_dir && parameters_file_append
if origin_file && File.exists?(origin_file)
relative_path = "app/config/parameters.yml"
files = [origin_file]
files << origin_file_append if origin_file_append && File.exists?(origin_file_append)
tmp_origin_file = origin_file + '.tmp'
File.open(tmp_origin_file, 'w') do |fo|
files.each do |file|
File.foreach(file) do |li|
fo.puts li
end
end
end
if shared_files && shared_files.include?(relative_path)
destination_file = shared_path + "/" + relative_path
else
destination_file = latest_release + "/" + relative_path
end
try_sudo "mkdir -p #{File.dirname(destination_file)}"
top.upload(tmp_origin_file, destination_file)
File.delete(tmp_origin_file)
end
end
end
Related
post '/uploadZIP' do
zipFile = params['zip'][:filename]
if zipFile.end_with? '.zip'
File.open(params['zip'][:filename], 'w') do |f|
f.write(params['zip'][:tempfile].read)
end
extract_zip(zipFile, '..\VotersBest\public')
$websites = get_websites()
redirect to('/loginTA')
end
end
#STORE WEBSITES IN ARRAY
def get_websites()
$directory = "public"
if Dir.exist? $directory
siteArray = Array.new
# go to pwd/dir
Dir.chdir($directory) { siteArray = Dir.glob("*").select {|x| Dir.exist? x }}
# go back to parent dir
siteArray
end
end
get '/websites' do
#instance_websites = $websites
#website_url = $directory+ "/"+ #instance_websites[0] + "/index.html"
erb :websites
end
it says sinatra doesnt know this ditty and i know thas because i dont have a get request but is there anyway to get around that? I have websites in different folders and I dont want to make a get request for each folder path
the line
#website_url = $directory+ "/"+ #instance_websites[0] + "/index.html"
gets the error
it says to try
get '/public/student1/index.html' do
"Hello World"
end
but there could be time where the folder isnt called "student"
In Ruby, how do I check if the file is newer than the target before copying?
I found in Ruby-doc.org the FileUtils.uptodate?, but it doesn't seems to work.
I have this error message when running:
/Users/bprov/.rvm/rubies/ruby-2.0.0-p451/lib/ruby/2.0.0/fileutils.rb:148:in uptodate?': undefined methodeach' for "/Users/bprov/folder2/homecontroller":String (NoMethodError)
from Test_Copy.rb:11:in block in <main>'
from Test_Copy.rb:6:inforeach'
from Test_Copy.rb:6:in `'
I have something like that:
require 'fileutils'
$sourcepath = "/Users/bprov/railsbridge"
$destinationpath = "/Users/bprov/folder2"
Dir.foreach($sourcepath) do |file|
if (file =~ /^\./ )
# Do nothing
else
puts file
if FileUtils.uptodate?($sourcepath + "/" + file, $destinationpath + "/" + file)
# Do nothing
else
# If newer
FileUtils.cp($sourcepath + "/" + file, $destinationpath + "/" + file)
end
end
end
So, just use it properly:
FileUtils.uptodate?($sourcepath + "/" + file, [$destinationpath + "/" + file])
I want to programmatically append a single-line of YAML front data to all the source _posts files.
Background: I currently have a Jekyll-powered website that generates its URLs with the following plugin:
require "Date"
module Jekyll
class PermalinkRewriter < Generator
safe true
priority :low
def generate(site)
# Until Jekyll allows me to use :slug, I have to resort to this
site.posts.each do |item|
day_of_year = item.date.yday.to_s
if item.date.yday < 10
day_of_year = '00'+item.date.yday.to_s
elsif item.date.yday < 100
day_of_year = '0'+item.date.yday.to_s
end
item.data['permalink'] = '/archives/' + item.date.strftime('%g') + day_of_year + '-' + item.slug + '.html'
end
end
end
end
end
All this does is generate a URL like /archives/12001-post-title.html, which is the two-digit year (2012), followed by the day of the year on which the post was written (in this case, January 1st).
(Aside: I like this because it essentially creates a UID for every Jekyll post, which can then be sorted by name in the generated _site folder and end up in chronological order).
However, now I want to change the URL scheme for new posts I write, but I don't want this to break all my existing URLs, when the site is generated. So, I need a way to loop through my source _posts folder and append the plugin-generated ULR to each post's YAML data, with the URL: front matter.
I'm at a loss of how to do this. I know how to append lines to a text file with Ruby, but how do I do that for all my _posts files AND have that line contain the URL that would be generated by the plugin?
Et voilĂ ! Tested on Jekyll 2.2.0
module Jekyll
class PermalinkRewriter < Generator
safe true
priority :low
def generate(site)
#site = site
site.posts.each do |item|
if not item.data['permalink']
# complete string from 1 to 999 with leading zeros (0)
# 1 -> 001 - 20 -> 020
day_of_year = item.date.yday.to_s.rjust(3, '0')
file_name = item.date.strftime('%g') + day_of_year + '-' + item.slug + '.html'
permalink = '/archives/' + file_name
item.data['permalink'] = permalink
# get post's datas
post_path = item.containing_dir(#site.source, "")
full_path = File.join(post_path, item.name)
file_yaml = item.data.to_yaml
file_content = item.content
# rewrites the original post with the new Yaml Front Matter and content
# writes 'in stone !'
File.open(full_path, 'w') do |f|
f.puts file_yaml
f.puts '---'
f.puts "\n\n"
f.puts file_content
end
Jekyll.logger.info "Added permalink " + permalink + " to post " + item.name
end
end
end
end
end
I wrote a script that I decided to refactor so I could add functionality to it as my coworkers think of it. I only saved four lines in the effort, but the main change is I removed both methods and reduced the number of called variables in favor of string interpolation/manipulation. Is there a preference for this? Is it better to declare a new variable just to use once, or is it more DRY to just make minor tweaks to the string when you need to use it? For example here is the original code:
def validate_directory(dir)
puts "Enter the full directory path of the flv files." unless dir
input = dir || gets.chomp
input.gsub!('\\', '/')
input += '/' unless input[-1..-1] == '/'
until File.directory?(input) && Dir.glob("#{input}*.flv") != []
puts "That directory either doesn't exist or contains no .flv files. \nEnter the full directory path of the flv files."
input = $stdin.gets.chomp
input.gsub!('\\', '/')
input += '/' unless input[-1..-1] == '/'
end
dir = input
end
def output(flv, location)
title = flv.dup.gsub!(".flv", ".html")
vid = flv.dup
vid.slice!(0..6)
body = $EMBED.gsub("sample.flv", vid)
htmlOutput = File.open(title, "w")
htmlOutput.write(body)
htmlOutput.close
linkList = File.open("#{location}List of Links.txt", "a")
linkList.write($BASE + vid.gsub(".flv", ".html") + "\n")
linkList.close
puts "Files created successfully."
end
dir = ARGV[0].dup unless ARGV.empty?
folder = validate_directory(dir)
files = folder.clone + "*.flv"
flvs = Dir.glob("#{files}")
File.delete("#{folder}List of Links.txt") if File.exists?("#{folder}List of Links.txt")
flvs.each { |flv| output(flv, folder) }
And the new stuff:
flash_folder = ARGV[0].dup unless ARGV.empty?
if !flash_folder
puts "Enter the full directory path of the flv files."
flash_folder = gets.chomp
end
flash_folder.gsub!('\\', '/')
flash_folder += '/' unless flash_folder[-1..-1] == '/'
until File.directory?(flash_folder) && Dir.glob("#{flash_folder}*.flv") != []
puts "That directory either doesn't exist or contains no .flv files. \nEnter the full directory path of the flv files."
flash_folder = $stdin.gets.chomp
flash_folder.gsub!('\\', '/')
flash_folder += '/' unless flash_folder[-1..-1] == '/'
end
flash_files = Dir.glob("#{flash_folder}*.flv")
File.delete("#{flash_folder}List of Links.txt") if File.exists?("#{flash_folder}List of Links.txt")
flash_files.each do |flv|
html_output = File.open("#{flv.gsub(".flv", ".html")}", "w")
html_output.write("#{embed_code.gsub("sample.flv", flv.slice(7..flv.length))}")
html_output.close
link_list = File.open("#{flash_folder}List of Links.txt", "a")
link_list.write("#{flash_url}#{flv.slice(2..flv.length).gsub(".flv", ".html")}\n")
link_list.close
end
puts "Finished."
I have a Ruby script that I built in TextMate and can successfully run in TextMate.
I can also successfully run this script straight from the terminal.
The script has this chunk of code in it:
# Get the XML file
puts 'Opening the file'
open("messages.xml", "r") do |f|
puts 'File is opened'
theXML = Hpricot::XML(f)
puts 'Trying to get the message_entity'
message_entity = GetMessage(theXML)
# Build the system command
puts 'Getting the author and the message'
theAuthor = message_entity.search(:author).text
theMessage = message_entity.search(:messagetext).text
# Get the correct image for this author
theAuthorImage = ''
case theAuthor
when 'James' : theAuthorImage = 'images/me32.png'
when 'Zuzu' : theAuthorImage = 'images/Zuzu32.png'
end
puts "/usr/local/bin/growlnotify '" + theAuthor + " says' -m '" + theMessage + "' -n 'Laurens Notes' --image '" + theAuthorImage + "'"
#system("/usr/local/bin/growlnotify '" + theAuthor + " says' -m '" + theMessage + "' -n 'Laurens Notes' --image '" + theAuthorImage + "'")
end
puts 'The End'
When the script is run by GeekTool, it never gets past puts 'File is opened'. It doesn't even hit puts 'The End'. It gives no error at all.
The script is under a folder under the /System folder on my Mac, but I have changed the file permissions to allow "everyone" to have "read & write" access.
EDIT
I just copied the files to a folder directly under my user home folder, and it still has the issue in GeekTool but not in TextMate or straight through the Terminal.
END EDIT
2nd Edit
I think GeekTool may have an issue with paths to files maybe.
For example, I changed the program to just read the XML file straight from the Internet for now and it does that just fine, but there are some images that the program is using for the icons in growlnotify. When run through TextMate, these icons display perfectly. When run using GeekTool...nope. No custom icon at all.
It's as if GeekTool just can't handle the file paths correctly.
When I do puts __FILE__.to_s it gives me the correct filepath to my .rb file though.
** end 2nd edit**
What should I do?
Geektool runs all the commands from / so relative path names will not work when trying to run growlnotify.
puts Dir.pwd #outputs "/"
You will need to pass the absolute paths of the images to growlnotify.
The current path can be retrieved with
File.dirname(__FILE__)
So you would use
theAuthorImage = File.dirname(__FILE__)
case theAuthor
when 'James' : theAuthorImage += '/images/me32.png'
when 'Zuzu' : theAuthorImage += '/images/Zuzu32.png'
end
cmd = "/usr/local/bin/growlnotify '#{theAuthor} says' -m '#{theMessage}' -n 'Laurens Notes' --image '#{theAuthorImage}'"
puts cmd
system cmd
Try wrapping it all in a block like below, which will log to /tmp/geektool.txt. Then you can see if there are any exceptions happening that you aren't aware of (like file permission).
begin
#file.open... etc
rescue Exception => e
file.open('/tmp/geektool.txt', 'w'){|f| f.puts "#{e}\n\n#{e.backtrace}"}
end
Also, don't forget there's the ruby-growl gem.
Have you checked if GeekTool spews any output to console.log or system.log?
Also, if it never gets past 'File is opened', it might be an issue with gems and requiring Hpricot?