How do I convert ~24000 product titles into URL keys? [closed] - ruby

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have an array with ~24000 products. The hash will be saved as a CSV and uploaded to a Shopify shop using the products import method.
When I manually create a single product, the product url key/handle is automatically generated based on the product title. When using the products import method (CSV), I'll have to specify it myself.
How do I convert the titles into product url keys?
Example:
title_1 = "AH Verse frietaardappelen"
url_key_1 = "ah-verse-frietaardappelen"
title_2 = "Lay's Sensations red sweet paprika"
url_key_2 = "lay-s-sensations-red-sweet-paprika"
I'm currently using:
<title>.downcase.gsub(' ','-').gsub("'", '-')
but this doesn't remove %, $, &, / etc. from the title. I want to make sure the url key/product handle is as clean as possible.
There must be a better way to do this, what could I try next?

There's a (private) to_handle method in Shopify's Liquid gem:
def to_handle(str)
result = str.dup
result.downcase!
result.delete!("'\"()[]")
result.gsub!(/\W+/, '-')
result.gsub!(/-+\z/, '') if result[-1] == '-'
result.gsub!(/\A-+/, '') if result[0] == '-'
result
end
Example:
to_handle("AH Verse frietaardappelen")
#=> "ah-verse-frietaardappelen"
to_handle("Lay's Sensations red sweet paprika")
#=> "lays-sensations-red-sweet-paprika"

Have a look at the gem String Urlize, it may help you write a script to do this.

I would suggest you to use Rails ActiveSupport::Inflector#parameterize solution - http://apidock.com/rails/ActiveSupport/Inflector/parameterize
It handles a lot of edge cases and should work well for you.

The best thing is to use parameterize method:
title_1 = "AH Verse $frietaardappelen".parameterize
Output: "ah-verse-frietaardappelen"
title_2 = "Lay's Sensations red %sweet paprika".parameterize
output: "lay-s-sensations-red-sweet-paprika"

Related

How to sort a list with and without links alphabetic in Notepad++? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I want to sort many lists alphabetic, but it doesn't work like I want, because some list items has a internal link and some items are not linked. Is it somehow possible to sort such lists, like I need it?
The output have to be in HTML code like my example list.
Here an example list:
<li>aaa</li>
<li>ddd</li>
<li>bbb</li>
<li>eee</li>
<li>ccc</li>
This should be the output
<li>aaa</li>
<li>bbb</li>
<li>ccc</li>
<li>ddd</li>
<li>eee</li>
Notepad++ might not get you there, but with a little javascript you can re-arrange the list in a test-page and copy/paste it, or simply re-arrange in place.
Essentially, the code gets all the LI elements contained within a target container. It then passes them to a compare function. If the element contains a link the link's text is used, otherwise, the LIs text is what the comparison is based on.
Other string comparison exercises focus on String.prototype.localeCompare, though I've used what's reported as being higher in performance.
"use strict";
window.addEventListener('load', onLoaded, false);
var strcmp = new Intl.Collator(undefined, {
numeric: true,
sensitivity: 'base'
}).compare;
function onLoaded(evt) {
var items = Array.from(document.querySelectorAll('li'));
var sorted = items.sort(compTextContent);
sorted.forEach(el => document.getElementById('output').appendChild(el.cloneNode(true)));
}
function compTextContent(a, b) {
var linkA = a.querySelector('a');
var linkB = b.querySelector('a');
a = (linkA ? linkA : a);
b = (linkB ? linkB : b);
return strcmp(a.textContent, b.textContent);
}
<div class='unsorted'>
<li>aaa</li>
<li>ddd</li>
<li>bbb</li>
<li>eee</li>
<li>ccc</li>
</div>
<hr>
<div id='output'>
</div>

Why it is showing `missing ',' before newline in composite literal` [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Why my vscode is showing this error
missing ',' before newline in composite literal
My code:
if title == "" && desc != "" {
msgs = database.UpdateNotification(&Notify, map[string]interface{}{
"Description": changedDesc,
}); msgs != nil {
log.Info("error while deleting notification")
}```
So you want to able to change the variable names dynamically?
There isnt any way of doing this. I suggest if you really need somthing like that you would use a Map.
Data map[String]String
Im not exactly sure what you need this for, or if this helps.

Is my syntax correct? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Could someone tell me if they see any syntax erros, I do not know lua and I am trying to make a small edit to an addon I use. If my syntax is incorrect could you please show me how to correct it and if it is correct could you please confirm that it is correct.
if(name) then
if(name == "SomebodiesName") then
name = name .. " (Udders! someone pop a gbank =)";
end
end
Error I recieve when trying to run the addon with this code added to it:
Message: REDACTED.lua:411: attempt to call field 'GT' (a nil value)
Count: 1
Stack: REDACTED.lua:411: in function <REDACTED.lua:410>
Locals: self = BuffCheck_MinimapButton {
0 = <userdata>
}
(*temporary) = nil
(*temporary) = "attempt to call field 'GT' (a nil value)"
The syntax of the code snippet you've shown looks okay, according to CodingGround, which is an excellent site to visit (a) if you need to check something quickly but you don't have a particular development environment just lying around.
name = "x";
if(name) then
if(name == "x") then
name = name .. " (Udders! someone pop a gbank =)";
end
end;
print(name);
That outputs:
x (Udders! someone pop a gbank =)
(whatever that means).
Given that the error seems to be about calling a field 'GT' which is set to nil and nowhere in your code snippet, I would suggest the problem lies elsewhere.
(a) My other favorites are SQLFiddle and JSFiddle.

Parsing gherkin into json [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am sure this is a very stupid question but I cannot get my head around it.
I have following ruby code:
sample_test = "Feature: Some terse yet descriptive text of what is desired
Textual description of the business value of this feature
Business rules that govern the scope of the feature
Any additional information that will make the feature easier to understand
Scenario: Some determinable business situation
Given some precondition
And some other precondition
When some action by the actor
And some other action
And yet another action
Then some testable outcome is achieved
And something else we can check happens too"
io = StringIO.new
pretty_formatter = Gherkin::Formatter::PrettyFormatter.new(io, true, false)
json_formatter = Gherkin::Formatter::JSONFormatter.new(io)
parser = Gherkin::Parser::Parser.new(json_formatter)
result = parser.parse(sample_test, '', 0)
This returns True.
But I want to get a JSON formatted result. What should I use to get JSON output of all the steps?
ok, I found it. This official example works pretty well:
require 'gherkin/parser/parser'
require 'gherkin/formatter/json_formatter'
require 'stringio'
require 'multi_json'
# This example reads a couple of features and outputs them as JSON.
io = StringIO.new
formatter = Gherkin::Formatter::JSONFormatter.new(io)
parser = Gherkin::Parser::Parser.new(formatter)
sources = ["features/native_lexer.feature", "features/escaped_pipes.feature"]
sources.each do |s|
path = File.expand_path(File.dirname(__FILE__) + '/../' + s)
parser.parse(IO.read(path), path, 0)
end
formatter.done
puts MultiJson.dump(MultiJson.load(io.string), :pretty => true)

Syntax issue with match method [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to match whatever word is after ">. This is my example text, and text to match.
example_text (a)
Text to grab:
example_text
Here's my code:
$page_html = Nokogiri::HTML.parse($browser.html)
$holder = $page_html.xpath('/html/body/div[2]/div[5]/div/table/tbody/tr[4]/td/a')
$user = $holder.match('(?<=\"\>)\w*')
And my error:
syntax error, unexpected tIDENTIFIER, expecting keyword_end
$user = $holder.match('(?<=\"\>)\w*')
^
I'm guessing the reason is the quotes interfering.
Your "unexpected tIDENTIFIER" error is coming from somewhere else, you should be getting an
undefined method `match' for #<Nokogiri::XML::NodeSet:...>
error since xpath gives you a Nokogiri::XML::NodeSet and those don't have match methods.
Your XPath expression appears to uniquely identify the single <a> you're after so you should just use at to get the node and then text to extract the content:
text = $page_html.at(...).text
Then you can simply split off the first word:
user = text.split.first
Also, you'll want to be careful with that XPath:
/html/body/div[2]/div[5]/div/table/tbody/tr[4]/td/a
That looks like it came from a browser and some browsers will insert <tbody> elements into <table>s but Nokogiri won't. You might need to adjust the XPath to match the real structure of the HTML you're scraping.
You must be missing a closing bracket somewhere earlier in your source. That is what it means when it says you're missing the keyword end.
2.0.0p0 :004 > $holder = 'example_text (a)'
=> "example_text (a)"
2.0.0p0 :005 > $user = $holder.match('(?<=\"\>)\w*')
=> #<MatchData "example_text">

Resources